Data Structure & Algorithm in Java

⌘K
  1. Home
  2. Docs
  3. Data Structure & Alg...
  4. Stack
  5. Stacks in java. util.

Stacks in java. util.

Here are the key explanation of Stacks in java. util.

  • In Java, the java.util package provides a class called Stack, 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 as ArrayDeque for stack operations. Deque stands for “double-ended queue” and can be used as both a stack (LIFO) and a queue (FIFO).
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.");
        }
    }
}

How can we help?

Leave a Reply

Your email address will not be published. Required fields are marked *