Tech and Media Labs
This site uses cookies to improve the user experience.




Java Collections - Stack

Jakob Jenkov
Last update: 2014-10-23

The java.util.Stack class deserves a little explanation on its own. In the text on the List interface the Stack class is listed as an implementation. The typical use of a Stack is not as a List though.

A Stack is a data structure where you add elements to the "top" of the stack, and also remove elements from the top again. This is also referred to as the "Last In First Out (LIFO)" principle. In contrast, a Queue uses a "First In First Out (FIFO)" principle.

Stack's are really handy for some types of data processing, for instance if you are parsing an XML file using either SAX or StAX. For an example, see my Java SAX Example in my Java XML tutorial.

Here is a Stack usage example:

Stack stack = new Stack();

stack.push("1");
stack.push("2");
stack.push("3");

//look at top object ("3"), without taking it off the stack.    
Object objTop = stack.peek();

Object obj3 = stack.pop(); //the string "3" is at the top of the stack.
Object obj2 = stack.pop(); //the string "2" is at the top of the stack.
Object obj1 = stack.pop(); //the string "1" is at the top of the stack.   

The push() method pushes an object onto the top of the Stack.

The peek() method returns the object at the top of the Stack, but leaves the object on of the Stack.

The pop() method returns the object at the top of the stack, and removes the object from the Stack.


Searching the Stack

You can search for an object on the stack to get it's index, using the search() method. The object's equals() method is called on every object on the Stack to determine if the searched-for object is present on the Stack. The index you get is the index from the top of the Stack, meaning the top element on the Stack has index 1.

Here is how you search a Stack for an object:

Stack stack = new Stack();

stack.push("1");
stack.push("2");
stack.push("3");

int index = stack.search("3");     //index = 1

Jakob Jenkov




Copyright  Jenkov Aps
Close TOC