StackTips

Stack in Java

siteadmin avtar

Written by

Stacktips,  4 min read,  106 views, updated on July 24, 2024

Stack extends Vector with five operations that allow a vector to be treated as a stack. It supports last-in, first-out (LIFO) operations.


Stack allows the following operations:

  • push(item): Adds an item to the top of the stack.
  • pop(): Removes and returns the item at the top of the stack.
  • peek(): Returns the item at the top of the stack without removing it.
  • empty(): Checks if the stack is empty.
  • search(item): Locates the presence of an item in the stack and it returns the distance from the top. If there are duplicate items it returns the top most occurrence.

As the Stack extends Vector, all the stack operations are synchronized and thread-safe.

For example, if you are implementing a text editor functionally, we need to track all type actions to allow undo/redo functionality. The Stack will be a good choice for such implementation.

public class _1a_TextEditor {  
    private final Stack<String> textStack = new Stack<>();  
    private final Stack<String> undoStack = new Stack<>();  

    public void type(String text) {  
        textStack.push(text);  
        undoStack.clear();  
    }  

    public void undo() {  
        if (!textStack.isEmpty()) {  
            String lastText = textStack.pop();  
            undoStack.push(lastText);  
        } else {  
            System.out.println("Nothing to undo.");  
        }  
    }  

    public void redo() {  
        if (!undoStack.isEmpty()) {  
            String lastUndoText = undoStack.pop();  
            textStack.push(lastUndoText);  
        } else {  
            System.out.println("Nothing to redo.");  
        }  
    }  

    public void display() {  
        System.out.println("Current Text: " + String.join("", textStack));  
    }  

    public static void main(String[] args) {  
        _1a_TextEditor editor = new _1a_TextEditor();  
        editor.type("Hello, ");  
        editor.type("world!");  
        editor.display();  

        editor.undo();  
        editor.display();  

        editor.redo();  
        editor.display();  

        editor.undo();  
        editor.undo();  
        editor.display();  

        editor.redo();  
        editor.display();  
    }  
}

Getting Started with Python - Beginners Guide

Python is a language with a simple syntax and a powerful set of libraries. It is an interpreted language, with a rich programming environment, including a robust debugger and profiler.

>> CHECK OUT THE COURSE

Continue reading..