All 15 Generics questions
More in Generics
Advertisement
Back to results for “Collections”
Java › Generics

How would you implement a generic Stack<T> class from scratch, demonstrating how a self-contained generic data structure is typically structured?

Intermediate

Answer

A generic Stack<T> declares its type parameter at the class level, uses it throughout the class's internal storage (commonly a generic ArrayList<T> or array-based structure) and public API (push(T item), T pop(), T peek()), giving compile-time type safety to any code using a specific instantiation like Stack<Integer> or Stack<String>, with the exact same single class definition serving every possible element type without any code duplication.
public class Stack<T> {
    private final List<T> elements = new ArrayList<>();

    public void push(T item) { elements.add(item); }

    public T pop() {
        if (elements.isEmpty()) throw new NoSuchElementException("Stack is empty");
        return elements.remove(elements.size() - 1);
    }

    public T peek() {
        if (elements.isEmpty()) throw new NoSuchElementException("Stack is empty");
        return elements.get(elements.size() - 1);
    }

    public boolean isEmpty() { return elements.isEmpty(); }
}

Stack<String> stack = new Stack<>();
stack.push("first");
String top = stack.pop();  // returns String directly, no cast needed
Real-world example An expression-evaluation engine implements a custom generic Stack<Token> to manage operator precedence during parsing, benefiting from the same single generic Stack implementation being reusable for entirely different purposes elsewhere in the codebase (like Stack<UndoAction> for an undo feature) without any code duplication.

Common follow-ups: How would you add a generic bound to this Stack to require elements be Comparable, enabling a max() method?;What's the performance/design trade-off of backing this Stack with an ArrayList versus a raw array with manual resizing?