CollectionsLists
Stack & Vector
Legacy synchronized collections, 1-based distance search methods, and modern ArrayDeque replacements
Both Vector and Stack are legacy classes dating back to Java 1.0. Every public method is synchronized, which introduces locking overhead on single-threaded workloads.
Vector<E>
Vector is a synchronized dynamic array that doubles its capacity (2x) when full.
Vector<String> v = new Vector<>();
v.add("x");
v.add("y");
// Legacy Enumeration style
Enumeration<String> e = v.elements();
while (e.hasMoreElements()) {
System.out.println(e.nextElement());
}Stack<E>
Stack extends Vector, inheriting synchronization and breaking encapsulation by allowing indexed access anywhere in the stack.
Stack<Integer> stack = new Stack<>();
stack.push(10);
stack.push(20);
int top = stack.peek(); // 20
int val = stack.pop(); // 20
boolean empty = stack.empty();
// 1-based distance from top
int depth = stack.search(10); // 1-based index (returns -1 if absent)| Method | Return Type | Empty Behavior | Notes |
|---|---|---|---|
push(E item) | E | — | Returns the item pushed |
pop() | E | Throws EmptyStackException | Removes and returns top item |
peek() | E | Throws EmptyStackException | Inspects top item |
empty() | boolean | — | Checks if stack contains zero items |
search(Object o) | int | — | 1-based distance from top; -1 if absent |
Modern Replacement: ArrayDeque
For any new Java application, prefer ArrayDeque over Stack:
// Clean, lock-free, optimal CPU cache locality
Deque<Integer> stack = new ArrayDeque<>();
stack.push(10);
stack.push(20);
int top = stack.peek(); // 20
int val = stack.pop(); // 20