GotchaDifficulty: Advanced1 min

Stack vs ArrayDeque: Why the Stack Class Should Not Be Used

It has push and pop, it is the first suggestion, and its own documentation points elsewhere.

java.util.Stack is a class from Java 1.0 that still works and should not be used. It extends Vector, so it carries every list operation a stack should refuse, and synchronises every method whether you need it or not. ArrayDeque, used through the Deque interface, is the replacement.

Autocomplete offers Stack the moment you type the word, and it has push and pop. 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

The inheritance is the problem: every Vector method is available, so a stack can be indexed, inserted into in the middle, and iterated from the bottom up.

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.