import java.util.ArrayList; class GenericStack<T> { private ArrayList<T> stack; // Constructor public GenericStack() { stack = new ArrayList<>(); } // Push method to add an element to the stack public void push(T value) { stack.add(value); } // Pop method to remove and return the top element of the stack public T pop() { if (isEmpty()) { throw new IllegalStateException("Stack is empty"); } return stack.remove(stack.size() - 1); } // Peek method to return the top element without removing it public T peek() { if (isEmpty()) { throw new IllegalStateException("Stack is empty"); } return stack.get(stack.size() - 1); } // Check if the stack is empty public boolean isEmpty() { return stack.isEmpty(); } // Get the size of the stack public int size() { return stack.size(); } } public class GenericStackDemo { public static void main(String[] args) { // Integer stack GenericStack<Integer> intStack = new GenericStack<>(); intStack.push(1); intStack.push(2); intStack.push(3); System.out.println("Top of Integer stack: " + intStack.peek()); System.out.println("Pop from Integer stack: " + intStack.pop()); System.out.println("Size of Integer stack: " + intStack.size()); // Double stack GenericStack<Double> doubleStack = new GenericStack<>(); doubleStack.push(1.1); doubleStack.push(2.2); doubleStack.push(3.3); System.out.println("Top of Double stack: " + doubleStack.peek()); System.out.println("Pop from Double stack: " + doubleStack.pop()); System.out.println("Size of Double stack: " + doubleStack.size()); // String stack GenericStack<String> stringStack = new GenericStack<>(); stringStack.push("Hello"); stringStack.push("World"); System.out.println("Top of String stack: " + stringStack.peek()); System.out.println("Pop from String stack: " + stringStack.pop()); System.out.println("Size of String stack: " + stringStack.size()); } }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter