🆚 Stack
vs ArrayDeque
— Why ArrayDeque
wins
1. ✅ Performance
Feature | Stack | ArrayDeque |
---|---|---|
Underlying base | Vector (synchronized) | Resizable array (not synchronized) |
Thread-safe? | Yes (but outdated style) | No (but faster in single-threaded use) |
Performance | Slower due to synchronization | Faster — no sync overhead |
🔧
ArrayDeque
avoids the cost of locking/unlocking thatStack
inherits fromVector
.
2. ✅ Cleaner, Modern API
ArrayDeque
implementsDeque
, so you get stack and queue methods:
push(), pop(), peek(), addFirst(), addLast(), removeFirst(), removeLast()
Stack
is limited to only:
push(), pop(), peek(), empty()
3. ✅ Better Design
Stack
is a legacy class:
- Inherits from
Vector
(a thread-safe, legacy list) - Brings in unwanted methods like
insertElementAt()
,elementAt()
, etc.
This goes against good object-oriented design — Stack
has more methods than it should, violating encapsulation.
👉 ArrayDeque
, by contrast, is a dedicated stack/queue structure with a clear, tight API.
4. ✅ No capacity limits or reallocation issues
Both Stack
and ArrayDeque
are resizable, but ArrayDeque
is:
- Backed by an efficient circular array
- Dynamically grows without copying every element
It’s tuned for fast push/pop performance on both ends.
📜 Java Docs Recommendation
Official JavaDoc:
“This class is likely to be faster thanStack
when used as a stack.”
📌 That’s why ArrayDeque
is now the recommended stack replacement in modern Java.
🧪 Example: ArrayDeque
as a Stack
Deque<String> stack = new ArrayDeque<>();
stack.push("A");
stack.push("B");
stack.push("C");
System.out.println(stack.pop()); // C