Clean • Professional
In Java, Stack is a class inside the java.util package and is considered a legacy collection. Even though Java provides modern alternatives like ArrayDeque, the Stack class is still widely used for learning and interviews.
A Stack is a LIFO (Last-In, First-Out) data structure where elements are added and removed only from the top.
It is a legacy class in Java, extends Vector, and is synchronized.
Iterable
└── Collection
└── List
└── Vector
└── Stack
Stack also inherits:
| Feature | Explanation |
|---|---|
| LIFO Structure | Last element added is the first removed |
| Thread-Safe | Inherited synchronization from Vector |
| Allows Null | Yes |
| Allows Duplicates | Yes |
| Legacy Class | Replaced by ArrayDeque in modern Java |
| Dynamic Size | Grows like Vector |
Use Stack when:
Avoid Stack when:
import java.util.Stack;
public class Main {
public static void main(String[] args) {
Stack<String> stack = new Stack<>();
stack.push("Java");
stack.push("Python");
stack.push("C++");
System.out.println(stack);
}
}
Output:
[Java, Python, C++]
push(E item)
Adds an element on top of the stack.
stack.push("HTML");
peek()
Returns the top element without removing it.
stack.peek();
pop()
Removes and returns the top element.
stack.pop();
remove(int index)
Removes element at specific index (inherited from Vector).
stack.remove(0);
search(Object o)
Returns 1-based position from top; returns -1 if not found.
stack.search("Java");
contains(Object o)
Checks if the element exists.
stack.contains("Python");
empty()
Checks if the stack is empty.
stack.empty();
size()
Returns number of elements.
stack.size();
| Operation | Time Complexity | Explanation |
|---|---|---|
| push() | O(1) | Insert at top |
| pop() | O(1) | Remove top |
| peek() | O(1) | Access top |
| search() | O(n) | Linear search |
| contains() | O(n) | Linear search |
| Feature | Stack | ArrayDeque |
|---|---|---|
| Legacy | Yes | No |
| Synchronized | Yes | No |
| Speed | Slower | Faster |
| Recommended | No | Yes |
| Implementation | Vector | Resizable array |