//--------------------------------------------------------------------------- // ArrayBndQueue.java by Dale/Joyce/Weems Chapter 5 // // Implements BoundedQueueInterface with an array to hold the queue elements. // // ajg version: formatting, private, capacity->size, if-then-else // Just the DWC (davis weird constructor) //--------------------------------------------------------------------------- package ch05.queues; public class ArrayBndQueue implements BoundedQueueInterface { private T[] queue; // queue elements private int numElements = 0; // number of elements n the queue private int front = 0; // index of front of queue private int rear; // index of rear of queue public ArrayBndQueue(T[] queue) { this.queue = queue; rear = queue.length - 1; } public boolean isEmpty() { return (numElements == 0); } public boolean isFull() { return (numElements == queue.length); } public void enqueue(T element) { // Throws QueueOverflowException if this queue is full; // otherwise, adds element to the rear of this queue. if (isFull()) throw new QueueOverflowException("Helpful message."); rear = (rear + 1) % queue.length; queue[rear] = element; numElements++; } public T dequeue() { // Throws QueueUnderflowException if this queue is empty; // otherwise, removes front element from this queue and returns it. if (isEmpty()) throw new QueueUnderflowException("Dequeue attempted on empty queue."); T ans = queue[front]; queue[front] = null; front = (front + 1) % queue.length; numElements--; return ans; } } // Local Variables: // compile-command: "cd ../../; javac ch05/queues/ArrayBndQueue.java" // End: