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("");

}

}

[5581 byte] By [dansinga] at [2007-11-27 7:07:01]
# 1
In your enqueue method there is not check to see if the number of items in the queue is equal or less than max items allowed. Is this allowed? If there are five items in the queue and you add a sixth, is it supposed to "push" the first off the queue?
floundera at 2007-7-12 18:58:20 > top of Java-index,Java Essentials,New To Java...