Stack
A stack is last-in, first-out storage: push adds to the top, pop removes the top. In Java, use ArrayDeque as a stack. The java.util.Stack class is a leftover synchronized Vector.
Detailed Explanation
Call stacks, undo history, DFS, and matching parentheses are stack-shaped. The last plate you set down is the first you pick up. The operations are push, pop, and peek. All are O(1) on a deque or on an array used from the end.
java.util.Stack extends Vector. Every method is synchronized. It also inherits Vector methods (insertElementAt, get) that break the stack contract. The Javadoc tells you to use Deque instead. ArrayDeque.push / pop / peek are the replacement. A raw ArrayList used only at size()-1 also works if you do not need the Deque type.
You still need the idea in interviews and in algorithms. Recursion is an implicit stack. An explicit stack lets you convert recursion to a loop, cap the depth, or store extra state per frame. DFS on a graph uses a stack (or recursion). BFS uses a queue. The choice of structure is the algorithm.
You reach for an explicit stack when the next item to process is the most recently discovered one, when you parse nested structures, or when you evaluate postfix. You reach for a queue when the next item is the oldest. You do not declare Stack<E> on new APIs; declare Deque<E> and construct an ArrayDeque.
The cost of java.util.Stack is a lock you do not need and a type that lies. The cost of a linked-list stack is node allocation. The cost of overflowing the call stack with recursion is StackOverflowError; an explicit heap stack grows until the heap is gone, which is usually farther.
pop and peek throw NoSuchElementException on an empty ArrayDeque. Check isEmpty or use pollFirst if emptiness is normal. Do not store null in an ArrayDeque.
Code Examples
import java.util.ArrayDeque;
import java.util.Deque;
public class Brackets {
static boolean balanced(String s) {
Deque<Character> stack = new ArrayDeque<>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '(') {
stack.push(c);
} else if (c == ')') {
if (stack.isEmpty()) {
return false;
}
stack.pop();
}
}
return stack.isEmpty();
}
public static void main(String[] args) {
System.out.println(balanced("(())")); // prints: true
System.out.println(balanced("(()")); // prints: false
}
}import java.util.ArrayDeque;
import java.util.Deque;
public class Undo {
public static void main(String[] args) {
Deque<String> undo = new ArrayDeque<>();
undo.push("type a");
undo.push("type b");
System.out.println(undo.pop()); // prints: type b
System.out.println(undo.peek()); // prints: type a
}
}Common Gotchas
Prefer `Deque` over `java.util.Stack`
`Stack` is synchronized `Vector` and exposes non-stack methods.
`pop` on empty throws
check `isEmpty` or use `pollFirst`.
Recursion uses the call stack
deep graphs need an explicit heap stack or you hit `StackOverflowError`.
`ArrayDeque` forbids null
use another structure if you must push nulls.