![]() |
VOOZH | about |
In Java, a Stack is a linear data structure that follows the Last In First Out (LIFO) principle and is defined in the java.util package. Internally, it extends the Vector class.
4 3 2 1
Explanation:
Note: The Stack class is a legacy class; in modern Java development, use ArrayDeque or LinkedList instead.
Stack class extends Vector, which extends Object
In order to create a Stack, we need to create an object of the Stack class. The Stack class inherits constructors from the Vector class.
This constructor is used to create an empty stack.
Stack<Integer> stack = new Stack<>();
This constructor is used to create a stack with a specified initial capacity.
Stack<Integer> stack = new Stack<>();
With the help of push() method we can add element to the stack. The push() method place the element at the top of the stack.
[4, All, Geeks] [Geeks, For, Geeks]
With the help of peek() method we can fetch the top element of the stack.
Initial Stack: [Welcome, To, Geeks, For, Geeks] The element at the top of the stack is: Geeks Final Stack: [Welcome, To, Geeks, For, Geeks]
With the help of pop() method we can delete and return the top element from the stack.
Initial Stack: [10, 15, 30, 20, 5] Popped element: 5 Popped element: 20 Stack after pop operation [10, 15, 30] Is stack empty? false Is stack empty? true
The Stack class in Java is inherits from Vector in Java. It is a thread-safe class. It is recommended to use ArrayDeque for stack implementation as it is more efficient in a single-threaded environment.
Using Stack (LIFO): 3 2 1 Using ArrayDeque (LIFO): 3 2 1
Method | Description |
|---|---|
This method returns true if the stack contains no elements at all, and false otherwise. It does not check the βtopβ element specifically. | |
This method returns the element on the top of the stack, but does not remove it. | |
This method removes and returns the top element of the stack. | |
This method pushes an element on the top of the stack. | |
This method is used to determine whether an object exists in the stack. If the element is found. It returns the position of the element from the top of the stack. Else, it returns -1. |