Sunday, December 21, 2008

Queue in Java


import java.util.ArrayList;

/*Queue
* implements a simple queue first in, first out
*/
public class Queue {

public Queue()
{

}

private ArrayList mItems = new ArrayList();

/* empty
* -returns true if there are 0 items in the queue
* other wise false
*/
public boolean empty()
{
return mItems.isEmpty();
}
/* size
* -returns the number of items in the queue
*/
public int size()
{
return mItems.size();
}
/*enqueue
* -adds a node to the back end of the queue
*
*/
public void enqueue(Object obj)
{
mItems.add(0,obj);
}
/*dequeue
* -removes the last Object from the inner list
* other words, pulls the first Object off the front of the queue
*/
public Object dequeue()
{
if (this.empty()) throw new EmptyQueueException();

return mItems.remove(mItems.size()-1);
}
/*peek
* -returns the front Object of the que
*/
public Object peek()
{
if (this.empty()) throw new EmptyQueueException();

return mItems.get(mItems.size()-1);
}

}

No comments: