Java Stack Examples: java.util.Stack

Use the Stack collection from java.util.Stack. Call push, pop and peek on the Stack.
Stack. This collection is implements LIFO: the last in is the first out. We push elements onto the top of a stack and then pop them for retrieval.
Deprecated. This collection is deprecated—its use is discouraged in favor of Deque. It is based on Vector, which has worse performance than newer lists.
An example. Let us begin working upon a Stack. We import java.util.Stack to make the Stack type accessible. We use diamond inference syntax to declare the stack.

Push: We invoke push() on the stack. When we push "fly" to the stack, the "fly" is at the top of the stack.

Then: When we push "worm" and "butterfly" to the stack, the fly is now at the bottom, and "butterfly" is at the top.

Peek: This returns (but does not remove) the topmost element of the stack (in this case "butterfly").

Pop: We call pop() twice to remove the topmost element, and then the new topmost element. We display both results.

Java program that uses Stack import java.util.Stack; public class Program { public static void main(String[] args) { Stack<String> stack = new Stack<>(); stack.push("fly"); stack.push("worm"); stack.push("butterfly"); // Peek at the top of the stack. String peekResult = stack.peek(); System.out.println(peekResult); // Pop the stack and display the result. String popResult = stack.pop(); System.out.println(popResult); // Pop again. popResult = stack.pop(); System.out.println(popResult); } } Output butterfly butterfly worm
Add, loop. A Stack is based on the Vector type. We can invoke all the Vector's methods: here we call add() instead of push() to add elements.

Loop: We can loop over a stack with its iterator in a for-loop. In this way we display all the Stack's elements.

Java program that uses add, loop import java.util.Stack; public class Program { public static void main(String[] args) { Stack<Integer> stack = new Stack<>(); stack.add(10); stack.add(20); stack.add(1, 100); // We can add at a position. // Loop over int values. for (int value : stack) { System.out.println(value); } } } Output 10 100 20
Avoid this collection. Stack is deprecated. It still exists in the Java libraries for compatibility. When I looked for a Stack collection, it appeared in Eclipse.

However: This is not the best stack-like collection. The ArrayDeque and the Deque interface are faster and newer.


Note: In my experience, when a framework redesigns collections and replaces them, the newer ones are consistently better.

Stack and queues. Implementing parsers is often done with stacks. When each element is encountered, it is pushed to the stack. In older programs, this Stack is used.
Dot Net Perls
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to