import java.util.ArrayList; //GenericArrayListStack public class GenericArrayListStack<T> { private ArrayList<T> stackList; public GenericArrayListStack() { stackList = new ArrayList<>(); } public void push(T value) { stackList.add(value); } public T pop() { if (isEmpty()) { System.out.println("Stack is empty."); return null; } else { return stackList.remove(stackList.size() - 1); } } public T peek() { if (isEmpty()) { System.out.println("Stack is empty."); return null; } else { return stackList.get(stackList.size() - 1); } } public boolean isEmpty() { return stackList.isEmpty(); } public int size() { return stackList.size(); } } //Main public class Main { public static void main(String[] args) { // Stack for Integers GenericArrayListStack<Integer> intStack = new GenericArrayListStack<>(); intStack.push(1); intStack.push(2); System.out.println(intStack.pop()); // Output: 2 System.out.println(intStack.peek()); // Output: 1 // Stack for Doubles GenericArrayListStack<Double> doubleStack = new GenericArrayListStack<>(); doubleStack.push(1.1); doubleStack.push(2.2); System.out.println(doubleStack.pop()); // Output: 2.2 System.out.println(doubleStack.peek()); // Output: 1.1 // Stack for Strings GenericArrayListStack<String> stringStack = new GenericArrayListStack<>(); stringStack.push("Hello"); stringStack.push("World"); System.out.println(stringStack.pop()); // Output: World System.out.println(stringStack.peek()); // Output: Hello } }
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