Here are the key explanation of Stacks in java. util.
- In Java, the
java.util
package provides a class calledStack
, which represents a last-in, first-out (LIFO) stack of objects. - However, it’s important to note that the
Stack
class is considered legacy and is not recommended for use in new code. - Instead, it is recommended to use the
Deque
interface and its implementations such asArrayDeque
for stack operations.Deque
stands for “double-ended queue” and can be used as both a stack (LIFO) and a queue (FIFO).
Here’s a brief overview of the Stack
class and its usage:
import java.util.Stack;
public class Main {
public static void main(String[] args) {
Stack<Integer> stack = new Stack<>();
// Push elements onto the stack
stack.push(1);
stack.push(2);
stack.push(3);
// Pop an element from the stack
int poppedElement = stack.pop();
System.out.println("Popped element: " + poppedElement);
// Peek at the top element of the stack
int topElement = stack.peek();
System.out.println("Top element: " + topElement);
// Check if the stack is empty
System.out.println("Is stack empty? " + stack.isEmpty());
// Search for an element in the stack
int index = stack.search(2);
if (index != -1) {
System.out.println("Element 2 found at index " + index + " from the top of the stack.");
} else {
System.out.println("Element 2 not found in the stack.");
}
}
}