Understanding Java Stack for DSA

A Stack in Java is a data structure that follows the Last-In-First-Out (LIFO) principle. This means that the last element added to the stack will be the first one to be removed. The Stack class in Java extends the Vector class, which means it inherits all the methods from Vector but is specifically designed to operate as a stack.

Key Characteristics

  1. LIFO Principle: The last element added to the stack is the first to be removed.

  2. Thread-Safe: Since Stack extends Vector, it is synchronized and thus thread-safe.

  3. Null Elements: Allows the storage of null values.

  4. Duplicates: Allows duplicate elements.

Constructor

  1. Stack(): Creates an empty stack.

     Stack<String> stack = new Stack<>();
    

Common Methods

  1. push(E item): Pushes an item onto the top of this stack.

     stack.push("Apple");
    
  2. pop(): Removes the object at the top of this stack and returns that object as the value of this function.

     String fruit = stack.pop();
    
  3. peek(): Looks at the object at the top of this stack without removing it from the stack.

     String fruit = stack.peek();
    
  4. empty(): Tests if this stack is empty.

     boolean isEmpty = stack.empty();
    
  5. search(Object o): Returns the 1-based position where an object is on this stack. If the object o occurs as an item in this stack, this method returns the distance from the top of the stack of the occurrence nearest the top of the stack; the topmost item on the stack is considered to be at a distance 1. If the object is not on the stack, it returns -1.

     int position = stack.search("Apple");
    

Iteration

Stack can be iterated using various methods such as for-each loop, iterators, and streams.

for (String item : stack) {
    System.out.println(item);
}    

Iterator<String> iterator = stack.iterator();
while (iterator.hasNext()) {
    System.out.println(iterator.next());
}

stack.forEach(System.out::println);

Performance Considerations

  1. Push/Pop/Peek: O(1)

  2. Search: O(n)

Thank you for reading!

You can support me by buying me a book.