The ArrayQueue Class
Here is the class, with its fields and constructor:
public class ArrayQueue<T> implements Queue<T> {
private T[] arr; // the backing array, used as a circular array
private int front; // the index of the front item
private int size; // how many items are in the queue
@SuppressWarnings("unchecked")
public ArrayQueue() {
arr = (T[]) new Object[10]; // start with room for 10 items
front = 0; // the front starts at index 0
size = 0; // the queue starts empty
}
// ... the operations will go here
}
There is no back field. As described earlier, the next free slot is computed as (front + size) % arr.length. The constructor uses the same unchecked cast as ArrayStack.
The isEmpty operation reads size directly:
@Override
public boolean isEmpty() {
return size == 0;
}
The front operation checks the contract first:
@Override
public T front() {
if (isEmpty()) {
throw new NoSuchElementException();
}
return arr[front]; // the front item is at index front
}
As with size and size() in the dynamic array chapter, the field front and the method front() can share a name.
The dequeue operation moves front around the circle:
@Override
public void dequeue() {
if (isEmpty()) {
throw new NoSuchElementException();
}
arr[front] = null; // clear the slot so the object can be garbage collected
front = (front + 1) % arr.length; // move front one position around the circle
size--;
}
Clearing the slot is the same cleanup we did in ArrayStack’s pop.