GotchaDifficulty: Advanced1 min

Why the Stack Class Still Exists, and What to Use Instead

Autocomplete offers Stack the moment you type the word, it has push and pop, and it is the wrong answer. It also prints in the opposite order from the one you would expect.

java
Stack<String> s = new Stack<>();
s.push("a"); s.push("b"); s.push("c");

System.out.println(s);
System.out.println(s.pop());
text
[a, b, c]
c

Stack extends Vector, a class from Java 1.0. That inheritance is the problem: every Vector method is on it, so a stack can be indexed, inserted into in the middle, and iterated from the bottom up — none of which a stack should permit.

What each class gives you for stack-like work
Compared onStackArrayDeque
Synchronised on every methodYes, whether or not you share itNo
Exposes positional accessYes, inherited from VectorNo
IteratesBottom to topTop to bottom, which is pop order
Recommended by its own documentationNo — it points at DequeYes

Use Deque<String> stack = new ArrayDeque<>() with push, pop and peek. It is faster, it iterates in pop order, and it refuses the operations a stack should refuse.