Card 06/ 08
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:
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]
cThe 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.
| 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.
← → move through sections and cards