Stack:
Stack in Java:
Stack:
Stack can be created using:Stack<Integer> stack = new Stack<>();
0.
Stack is implemented as a subclass of Vector, which uses a
dynamic array to store elements.
Top β [ ]
Stack:
push() method:stack.push(10);stack.push(20);stack.push(30);stack.push(40);stack.push(50);stack.push(60);
peek() method returns the top element without removing it.System.out.println(stack.peek()); // prints 60
Stack: pop() method removes and returns the top element of the stack.int top = stack.pop(); // Removes 60
Stack:
search() method returns position (1-based) of an element from the top of the stack.System.out.println(stack.search(20)); // returns 4 because 60 has been removed from stack
-1.
Stack is Empty:
empty() method checks whether the stack is empty.System.out.println(stack.empty()); // false
Stack:
Vector, it can be traversed using Iterator or a for-each loop.
for (Integer no : stack)
{
System.out.println(no);
}
Stack are synchronized because it extends Vector.
Deque or ArrayDeque.
Deque<Integer> stack = new ArrayDeque<>();
stack.push(10);
stack.push(20);
System.out.println(stack.pop());
Stack is Good for:
Stack follows the LIFO principle β the last element added is the first one removed.
Stack extends Vector, all its methods are synchronized.
push(), pop(), peek(), and search() for managing stack elements.
Deque and ArrayDeque.
Stack is Not Good for:
ArrayDeque is much faster for single-threaded stack operations.
Stack class only supports basic stack operations (push, pop, peek, search).
ConcurrentLinkedDeque or BlockingDeque.
Deque or ArrayDeque since Java 1.5.
search() method performs a linear search (O(n)) starting from the top of the stack.
| Operation | Description | Performance / Complexity |
|---|---|---|
push(E item) |
Adds an element to the top of the stack. | O(1) |
pop() |
Removes and returns the top element. | O(1) |
peek() |
Returns the top element without removing it. | O(1) |
search(Object o) |
Searches the element from top to bottom (1-based index). | O(n) |
empty() |
Checks if the stack is empty. | O(1) |
Traversal |
Can use Iterator or for-each loop. |
O(n) |
Thread Safety |
Yes (inherited synchronized methods from Vector). |
Overhead present |
Your feedback helps us grow! If there's anything we can fix or improve, please let us know.
Weβre here to make our tutorials better based on your thoughts and suggestions.