understanding queues
I'm trying to better understand this program. It's an array based implementation of a queue. In the code below, I don't understand how I can add more than the mazsize to the array...I've added other elements, such as 90 and 91 and the size now equals 7, but this line tells me it should only be 5?
AQueue2 theQueue = new AQueue2(5); // queue holds 5 items
Also I'd like to understand the enqueue method better...why is the tail set to -1?
Thanks, Dansing
publicclass AQueue2{
privateint maxSize;// maz size of the queue
privatelong[] qArray;// array base to holds elements for queue
privateint head;// head of the queue
privateint tail;// tail of the queue
privateint nItems;// total number of items in queue
public AQueue2(int s){
maxSize = s;
qArray =newlong[maxSize];// new array
head = 0;
tail = -1;
nItems = 0;
}
// put item at end of a queue
publicvoid enqueue(long j){
if (tail == maxSize - 1)// deal with wraparound
tail = -1;
qArray[++tail] = j;// increment rear and insert
nItems++;
}
// take item from front of queue
publiclong dequeue(){
long temp = qArray[head++];// get value and incr head
if (head == maxSize)// deal with wraparound
head = 0;
nItems--;// one less item
System.out.println("what is temp? " + temp);
return temp;
}
publiclong peekhead(){
return qArray[head];
}
publicboolean isEmpty(){
return (nItems == 0);
}
publicboolean isFull(){
return (nItems == maxSize);
}
publicint size(){
//System.out.println("what is the size? " +nItems);
return nItems;
}
publicstaticvoid main(String[] args){
AQueue2 theQueue =new AQueue2(5);// queue holds 5 items
theQueue.enqueue(10);
theQueue.enqueue(20);
theQueue.enqueue(30);
theQueue.enqueue(40);
System.out.println(theQueue.peekhead());// what element is at the head of the queue?
System.out.println(theQueue.size());// what is the size of the queue?
theQueue.dequeue();
theQueue.dequeue();
theQueue.dequeue();
theQueue.enqueue(50);
theQueue.enqueue(60);// (wraps around)
theQueue.enqueue(70);
theQueue.enqueue(80);
System.out.println(theQueue.peekhead());// what element is at the head of the queue?
System.out.println(theQueue.size());// what is the size of the queue?
theQueue.enqueue(90);
theQueue.enqueue(91);
System.out.println(theQueue.peekhead());
System.out.println(theQueue.size());
while (!theQueue.isEmpty()){
long n = theQueue.dequeue();// (40, 50, 60, 70, 80)
System.out.print(n);
System.out.print(" ");
}
System.out.println("");
}
}

