Deque as Stack
Master the modern, recommended way to implement a stack in Java using ArrayDeque: push, pop, and peek with confidence.
What Is a Stack?
A stack is a linear data structure that follows the Last-In, First-Out (LIFO) principle: the most recently added element is the first one removed.
Three Core Operations
Why Not java.util.Stack?
The legacy Stack class extends Vector, which means every operation is synchronized (thread-safe locking), adding unnecessary overhead for single-threaded programs.
Enter ArrayDeque
ArrayDeque implements the Deque interface, which stands for "Double-Ended Queue." When used as a stack, you only interact with one end: the top.
The Formal Declaration
Stack vs Queue vs Deque
| Stack (LIFO) | Queue (FIFO) | Deque (Both) | |
|---|---|---|---|
| Add | push(e) | offer(e) | push / offer |
| Remove | pop() | poll() | pop / poll |
| Inspect | peek() | peek() | peek / peekLast |
| Order | Last-In, First-Out | First-In, First-Out | Either end |
| Java class | ArrayDeque | LinkedList | ArrayDeque |
How to Apply It
Example 1: Reverse a String
Push every character onto the stack, then pop them all off. Since the stack is LIFO, the characters come out in reverse order.
Tracing the Reverse
Example 2: Balanced Brackets
A classic stack problem: given a string of brackets, determine if every opening bracket has a matching closing bracket in the correct order.
Example 3: Undo History
Every action is pushed onto the stack. When the user presses Undo, pop the most recent action. Peek shows the current state.
Inside push()
pop() vs peek() on Empty
| Method | Non-Empty Stack | Empty Stack |
|---|---|---|
| push(e) | Adds to top | Adds to top (stack now has 1 element) |
| pop() | Returns + removes top | NoSuchElementException |
| peek() | Returns top (no removal) | Returns null |
| isEmpty() | false | true |
| size() | Number of elements | 0 |
Common Mistakes
Summary Cheat Sheet
Question 1 of 5
Which is the recommended way to declare a stack in modern Java?
Question 2 of 5
What does stack.pop() return when called on an empty ArrayDeque?
Question 3 of 5
Consider the following code:
Deque<Integer> stack = new ArrayDeque<>();
stack.push(10);
stack.push(20);
stack.push(30);
stack.pop();
stack.push(40);
System.out.println(stack.peek());
What is printed to the console?
Question 4 of 5
Why is java.util.Stack considered a poor choice for implementing a stack?
Question 5 of 5
Which method should you call to check if the stack is empty before calling pop()?