Cover Image for Java Stack
109 views

Java Stack

The Stack class in Java is a subclass of Vector that implements the stack data structure. A stack is a collection that follows the “last-in, first-out” (LIFO) principle, where the last element added to the stack is the first one to be removed. The Stack class provides methods for the typical operations associated with a stack, such as pushing (adding) elements onto the stack and popping (removing) elements from the top of the stack.

Here are some key methods provided by the Stack class:

  1. push(E item): Adds an element to the top of the stack.
  2. pop(): Removes and returns the top element of the stack.
  3. peek(): Returns the top element of the stack without removing it.
  4. isEmpty(): Checks if the stack is empty.
  5. search(Object o): Searches for the given object in the stack and returns its position (distance from the top of the stack). If not found, it returns -1.

Here’s an example of how you might use the Stack class:

import java.util.*;

public class StackExample {
    public static void main(String[] args) {
        Stack<String> stack = new Stack<>();

        stack.push("First");
        stack.push("Second");
        stack.push("Third");

        System.out.println("Top element: " + stack.peek()); // Output: Third

        System.out.println("Stack size: " + stack.size()); // Output: 3

        while (!stack.isEmpty()) {
            System.out.println("Popped: " + stack.pop());
        }
    }
}

Keep in mind that while the Stack class can be used to implement a stack data structure, it is recommended to use the Deque implementations, such as ArrayDeque, for stack operations. The ArrayDeque class provides better performance and is more versatile as it can also be used as a queue or double-ended queue. The Stack class’s inheritance from Vector can introduce synchronization overhead that might not be needed for all scenarios.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS