Video in progress
Why is ArrayDeque recommended instead of the Stack class?
Stack is an old class that extends Vector: every method is synchronized, and the index methods inherited from Vector let you break the stack discipline. ArrayDeque is faster and gives you clean push/pop/peek through the Deque interface.
📖 Answer
Deque<Character> stack = new ArrayDeque<>();
stack.push('(');
stack.push('[');
stack.pop(); // '['
stack.peek(); // '('
Problems with Stack:
- since it comes from
Vector, you can callstack.add(0, x)orstack.get(3), and that is not a stack anymore; - every call takes a lock, which is pure overhead on a single thread;
- iteration goes from bottom to top, while in
ArrayDequeit goes from top to bottom, which gives surprising results.
ArrayDeque is built on a circular array, and adding and removing at both ends is O(1). It does not accept null elements. It is not thread-safe; if you need multiple threads, there are ConcurrentLinkedDeque and LinkedBlockingDeque.
Sign up to mark studied questions and save your progress.