Java's Stack Class
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
Stack is not as 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.
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.
push() method pushes an object onto the top of the
peek() method returns the object at the top of the
leaves the object on of the
pop() method returns the object at the top of the
and removes the object from the
Searching the Stack
You can search for an object on the stack to get it's index, using the
method. The object's
equals() method is called on every object on the
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
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 = 3