Collections Framework
Stack
Analyze the Stack legacy LIFO implementation, its inheritance issues, and modern Deque alternatives.
Interview: Focuses on why Stack extends Vector, Vector-to-Stack inheritance violations, and Deque stack operations.
The Stack class represents a Last-In-First-Out (LIFO) stack of objects. It extends the Vector class, which is widely considered an inheritance design flaw since stacks should not expose positional array mutations.
LIFO Operations
Supports standard LIFO actions: push, pop, peek, empty, and search.
Vector Inheritance
Inherits all index-based mutating operations (like insertElementAt) from Vector, exposing internal state.
Synchronization Cost
Inherits Vector's synchronized methods, causing locking overheads for every push and pop.
The Design Flaw of java.util.Stack
Exposing index-based operations on a stack violates basic encapsulation:
- Developers can call
stack.insertElementAt(item, index)orstack.remove(index), breaking the LIFO contract. - A true stack should only allow interaction via
push,pop, andpeek.
Common Pitfalls
- Modifying Stack index directly: Accessing stack elements by index using inherited methods, introducing logical bugs into parser systems.
- Empty Stack Pops: Invoking
pop()on an empty Stack, which raises anEmptyStackException.
Best Practices
- Use Deque for Stacks: Use the
Dequeinterface and its implementations (e.g.ArrayDeque) for stack structures:Deque<Integer> stack = new ArrayDeque<>(). - Check empty first: Always check if stack is empty (
isEmpty()) before calling pop or peek.
Interview-Relevant Information
Q1: Why is Stack considered a poorly designed class?
Answer: It extends Vector instead of using composition. As a result, it inherits all index-based mutation methods (like insertElementAt), which violates the strict LIFO constraint of a stack and breaks encapsulation.
Q2: What is the modern alternative to java.util.Stack in Java?
Answer: The Deque interface and its implementation ArrayDeque. ArrayDeque is unsynchronized and does not expose index-based mutations, serving as a faster and cleaner stack structure.
Quick Checklist
Can you identify the base class of Stack, explain why inheriting from it is a design flaw, and write a modern stack declaration using ArrayDeque? If yes, you understand Stack.
Use Cases
Parsing expressions and bracket matching algorithms in compilers.
Building backward-navigation histories (undo/redo) in desktop apps.
Common Mistakes
Using java.util.Stack classes in modern application designs.
Calling vector mutation operations on stack elements.