public void enqueue(Object obj)
{
        if(count == size) 
            throw new ContainerFullException();
        else 
        {
            array[rear] = obj;
            rear = (rear + 1) % size;
            count++;
        }

 }

this is a code that add and object to a circular array.at the start the array is empty,rear=front=0.
when we add the first element rear=1,front=0.
does the front points to null?

No, the front is pointing to the first index that contains the data, and the rear is pointing to the index right after the last index where the last data in the queue is. The way this circular array works is to use 2 main variables to keep tracks of where the data are at -- front & rear. For convenience, you could have count variable for a quick check (as in the code). The size variable is a fixed variable (somewhat constant).

Edited 4 Years Ago by Taywin

didnt get it,if rear is pointing to the next index and this is index=null; how can rear point to null?

The rear index is NOT being used in dequeue, only the front index is used. The rear index is used in enqueue only. OK, I will try to show it graphically.

/*
A queue length of 5 (an array structure)
+---+---+---+---+---+
| n | n | n | n | n |     n is null
+---+---+---+---+---+
  0   1   2   3   4
  ^
  |
front
rear
*/

//In your code to see if queue is empty, you would check for indices.
if(front==rear && array[front]==null) { return true; }

//In your code to see if queue is full, you would check for indices.
if(front==rear && array[front]!=null) { return true; }

/*
Now see when you put something in the queue.
+---+---+---+---+---+
| x | n | n | n | n |     n is null, x is not null
+---+---+---+---+---+
  0   1   2   3   4
  ^   ^
  |   |
front |
     rear

The rear index is pointing to the next index which is null, but
  the way you dequeue from the queue is always from the front index,
  not rear.
*/
if(array[front]!=null) {
  // get the item at the front index
  // increment the front index
  // return the item
}
else {
  // the queue is empty, handle it
}

/*
Now look at how it works when it gets to circulate point
+---+---+---+---+---+
| x | x | x | x | n |     n is null, x is not null
+---+---+---+---+---+
  0   1   2   3   4
  ^               ^
  |               |
front             |
                rear

Add one more object, it will be full...
+---+---+---+---+---+
| x | x | x | x | x |     n is null, x is not null
+---+---+---+---+---+
  0   1   2   3   4
  ^
  |
front
rear

If you attempt to enqueue one more, the queue should display the error
  (The queue is full).

The way you enqueue it would be similar to...
*/
if (array[rear]==null) {
  // add the object to the array
  // increment the rear
}
else {
  // the queue is full, handle it
}

Edited 4 Years Ago by Taywin

This article has been dead for over six months. Start a new discussion instead.