import java.util.NoSuchElementException; public class ArrayQueue implements Queue { final static int DEFAULT_CAPACITY= 16; private Object[] queue; private int front; private int rear; private int capacity; private int size = 0; public ArrayQueue( int cap ) { capacity = cap; front = 0; rear = capacity - 1; queue= new Object[capacity]; } public ArrayQueue() { this( DEFAULT_CAPACITY ); } public void add(Object o) { if ( size == capacity ) grow(); rear = ( rear + 1 ) % capacity; queue[ rear ] = o; size++; } public Object remove() throws NoSuchElementException { if ( isEmpty() ) throw new NoSuchElementException(); else { Object ret = queue[ front ]; queue[ front ] = null; // for garbage collection front = (front + 1) % capacity; size--; return ret; } } public boolean isEmpty() { return ( size == 0 ); } public void clear() { size = 0; front = 0; rear = capacity - 1; for ( int i = 0; i < capacity; i++ ) queue[ i ] = null; // for garbage collection } private void grow() { Object[] old= queue; int oldCapacity= capacity; capacity *= 2; queue= new Object[capacity]; if ( size == 0 ) return; if ( front <= rear ) { System.arraycopy(old, front, queue, front, size ); } else if ( rear < front ) { System.arraycopy(old, 0, queue, 0, rear + 1); System.arraycopy(old, front, queue, front + oldCapacity, oldCapacity - front ); front += oldCapacity; } } }