Sobes.tech
Senior

How to make a stack universal for working not only with Integer but also with String and custom objects?

sobes.tech AI

Answer from AI

To make a stack generic and work with any data types (Integer, String, custom objects), Java uses generics.

Example of a generic stack:

public class Stack<T> {
    private List<T> elements = new ArrayList<>();

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

    public T pop() {
        if (elements.isEmpty()) {
            throw new EmptyStackException();
        }
        return elements.remove(elements.size() - 1);
    }

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

Now you can create stacks for any type:

Stack<Integer> intStack = new Stack<>();
Stack<String> stringStack = new Stack<>();
Stack<MyObject> objectStack = new Stack<>();