Queue Code
/**
* Queue.java - a queue of Objects
*
* @author Todd Neller
* @version 1.0
*
Copyright (C) 2003 Todd Neller
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
Information about the GNU General Public License is available online at:
http://www.gnu.org/licenses/
To receive a copy of the GNU General Public License, write to the Free
Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
02111-1307, USA.
*/
public class Queue{
/**
* variable data
- an array that holds oll of
* the objects that are in the queue. */
private Object[] data;
/**
* variable head
- keeps track of which
* element is currently at the front of the line. */
private int head = 0;
/**
* variable tail
- keeps track of which
* element is currently at the back of the line. */
private int tail = 0;
/**
* variable items
- the number of objects
* currently held in the queue. */
private int items = 0;
/**
* Creates a new Queue
instance - this is
* fixed size queue that will overwrite existing objects
* if its size limit is exceeded.
*
* @param _numnodes an int
value - the max
* number of objects in the queue. */
public Queue(int _numnodes) {
data = new Object[_numnodes];
}
/**
* isEmpty
- test whether or not the queue
* is empty.
*
* @return a boolean
value */
public boolean isEmpty() {
return (items == 0);
}
/**
* enqueue
- add an object to the tail of the
* queue. If the fixed size of the queue is exceeded then
* enqueue will overwrite existing objects.
*
* @param item an Object
value - the object
* being enqueued. */
public void enqueue(Object item) {
//check to see if it's already there
for(int i = 0; i < data.length; i++) {
if(item.equals(data[i]))
return;
}
//enqueue new item
data[tail] = item;
items++;
tail++;
if (tail == data.length)
tail = 0;
}
/**
* dequeue
remove an object from the head of
* of the queue.
*
* @return an Object
value - the object being
* dequeued. */
public Object dequeue() {
// check for empty queue case
if (items == 0) return null;
// remove and return dequeued object
Object answer = data[head];
data[head] = null; // allows garbage collection
items--;
head++;
if (head == data.length)
head = 0;
return answer;
}
/**
* size
- return the number of items in the queue
*
* @return an int
value - number of items in the
* queue */
public int size() {
return items;
}
/**
* toString
- return a String representation of the
* queue.
*
* @return a String
value */
public String toString() {
String s = "";
for (int count = 0; count < items; count++) {
s+= data[count];
}
return s;
}
public static void main(String[] args) {}
} // Queue