Card 06/ 08
All 8 cards
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.
Stack<String> s = new Stack<>();
s.push("a"); s.push("b"); s.push("c");
System.out.println(s);
System.out.println(s.pop());[a, b, c]
cStack 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.
| Compared on | Stack | ArrayDeque |
|---|---|---|
| Synchronised on every method | Yes, whether or not you share it | No |
| Exposes positional access | Yes, inherited from Vector | No |
| Iterates | Bottom to top | Top to bottom, which is pop order |
| Recommended by its own documentation | No — it points at Deque | Yes |
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.