next up previous index
Next: Demonstration Up: Queues Previous: Interface   Index


Implementation

An implementation of the interface is given in Figure 3.3.

Figure 3.3: An implementation of the Queue interface using a variable length array.
import java.util.NoSuchElementException;

public class QueueArray implements Queue {

    private Object[] queue;
    private int size; // size of the queue
    private int top;  // for next insertion
    private int base; // for next removal

    public QueueArray() {
        queue = new Object[1];
        size = top = base = 0; 
    }
  
    public boolean isEmpty() {
        return size == 0;
    }
  
    public void enqueue(Object item) {
        if (size == queue.length) {
            // expand the queue
            Object[] newQueue = new Object[2*queue.length];
            System.arraycopy(queue, base, newQueue, 0, size-base);
            System.arraycopy(queue, 0, newQueue, size-base, base);
            queue = newQueue;
            base = 0;
            top = size;
        }
        queue[top++] = item;
        if (top == queue.length) {
            top = 0;
        }
        ++size;
    }

    public Object dequeue() {
        if (size == 0) {
            throw new NoSuchElementException();
        } else {
            Object item = queue[base++];
            if (base == queue.length) {
                base = 0;
            }
            --size;
            return item; 
        }
    }
}

The only new complication is the expansion of the queue array in the enqueue method. If the current queue array is full, we double its size and copy the old array into the new array. But the base of the old queue need not be at 0. So we must copy the array in two blocks, first from base upwards and then from 0 up to, but not including, base. (Note that top == base when the queue is full.) These blocks must be contiguous in the new array, and they may as well begin as 0. (See the documentation on arraycopy to confirm the role of its arguments.) If the queue is not full, we skip straight to the last three lines of code, which are executed in either case.



Peter Williams 2005-06-07