// Queue using an integer array public class Queue { // Constant specifying the maximum queue size public static final int DEFAULT_SIZE = 1000; // Internal (hidden) representation is an array private int[] q; // Index of front of queue private int qFront; // Number of elements in this queue private int qSize; // Maximum size of this queue private int maxSize; // Construct a queue of default size public Queue() { this( DEFAULT_SIZE ); } // Construct a queue public Queue( int size ) { this.q = new int[size]; this.qFront = this.qSize = 0; this.maxSize = size; } // Determine if this queue is empty public boolean isEmpty() { return ( this.qSize == 0 ); } // Add an element to the end of this queue public void add( int x ) { if ( this.qSize < this.maxSize ) { int i = ( this.qFront + this.qSize ) % this.maxSize; this.q[i] = x; this.qSize++; System.out.println( "ADDED " + x ); } else { // ERROR System.out.println( "FULL - CANNOT ADD " + x ); } } // Remove an element from the head of this queue public int remove() { if ( this.qSize == 0 ) { // ERROR System.out.println( "EMPTY!" ); return -1; } else { int x = this.q[this.qFront]; this.q[this.qFront] = 0; this.qFront = ( this.qFront + 1 ) % this.maxSize; this.qSize--; System.out.println( "REMOVED " + x ); return x; } } public static void main(String[] args) { System.out.println( "Default queue size is " + Queue.DEFAULT_SIZE ); Queue q1 = new Queue(3); // 7 if ( q1.isEmpty() ) { q1.add( 12 ); q1.add( 34 ); int x = q1.remove(); q1.add( 36 ); q1.add( 17 ); q1.add( 14 ); x = q1.remove(); x = q1.remove(); x = q1.remove(); x = q1.remove(); } } }