CODE
public class CircularQueue {
/** Array of references to the objects being queued. */
protected Object queue[] = null;
/** The array index for the next object to be stored in the queue. */
protected int sIndex;
/** The array index for the next object to be removed from the queue. */
protected int rIndex;
/** Number of objects currently stored in the queue. */
protected int count;
/** The number of objects in the array (Queue size + 1). */
protected int qSize;
/**
* Creates a circular queue of size s (s objects).
*
* @param s The maximum number of elements to be queued.
*/
public CircularQueue(int s) {
qSize = s + 1;
sIndex = 0;
rIndex = qSize;
count = 0;
queue = new Object[qSize];
}
/**
* Stores an object in the queue.
*
* @param x The object to be stored in the queue.
* @return true if successful, false otherwise.
* @exception ArrayIndexOutOfBoundsException
*/
public boolean put(Object x) throws ArrayIndexOutOfBoundsException {
if ((sIndex + 1 == rIndex) ||
((sIndex + 1 == qSize ) && (rIndex == 0))) {
// queue is full
return false;
} else {
// insert object into queue.
queue[sIndex++] = x;
count++;
if (sIndex == qSize) {
// loop back
sIndex = 0;
}
}
return true;
}
/**
* Removes an object from the queue.
*
* @return a reference to the object being retrieved.
* @exception ArrayIndexOutOfBoundsException
*/
public Object get() throws ArrayIndexOutOfBoundsException {
if (rIndex == qSize) {
// loop back
rIndex = 0;
}
if (rIndex == sIndex) {
// queue is empty
return null;
} else {
// return object
count--;
Object obj = queue[rIndex];
queue[rIndex] = null;
rIndex++;
return obj;
}
}
/**
* Returns the total number of objects stored in the queue.
*
* @return The total number of objects in the queue.
*/
public int getCount() {
return count;
}
/**
* Checks to see if the queue is empty.
*
* @return true if queue is empty, false otherwise.
*/
public boolean isEmpty() {
return (count == 0 ? true : false);
}
}
there was a problem on here...
but i still confuse with it...
the program still broken..
This post has been edited by ioncrew: 15 Mar, 2008 - 09:19 AM