What is the difference between a Stack and a Queue?

Brandon Rohlfs

First things first. Where can Stacks and Queue's be found? Java provides a Stack class, which can be found within the java.util namespace. Within the same namespace you will find a Queue interface. All concrete Queue implementations can be located within the java.util.concurrent package.

What is a Stack?

Java's Stack class extends the Vector class. A Stack represents a Collection of objects that are in LIFO (Last In First Out Order). The Stack class provides operations that allow testing for zero elements, inspection of it's top most element, removal of it's top most element, and the addition of elements.

boolean empty() Tests if this stack is empty.
E peek() Looks at the object at the top of this stack without removing it from the stack.
E pop() Removes the object at the top of this stack and returns that object as the value of this function.
E push(E item) Pushes an item onto the top of this stack.
int search(Object o) Returns the 1-based position where an object is on this stack.

What is a Queue?

A Queue is also a Collection of Objects similar to a Stack. Queues typically order the elements contained within in FIFO order but this is not always the case. Elements that are inserted into a Queue are inserted at the tail end as opposed to a Stack where the elements are pushed into it at the head. Looking at the Queue interface the operations are similar to what a Stack provides.

E element() Retrieves, but does not remove, the head of this queue.
boolean	offer(E o) Inserts the specified element into this queue, if possible.
E peek() Retrieves, but does not remove, the head of this queue, returning null if this queue is empty.
E poll() Retrieves and removes the head of this queue, or null if this queue is empty. 
E remove() Retrieves and removes the head of this queue.

So what are the differences between Queues and Stacks?

Besides how each order their elements there really isn't much difference. Both provided pretty much the same operations. The big difference is that one is a concrete implementation (Stack) while the other is an interface (Queue) thus implying that additional functionality is provided by the concrete classes that implement the Queue interface such as blocking, and synchronization.

0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact