simple array

  • This implementation has one negative aspect—it relies on a fixed-capacity array, which limits the ultimate size of the stack.
public interface Stack<E> {
    int size();
    boolean isEmpty();
    void push(E e);
    E pop();
    E top();
}
public class ArrayStack<E> implements Stack<E> {
    public static final int CAPACITY = 100;
    private E[] data;
    private int t;

    public ArrayStack(int capacity) {
        data = (E[]) new Object[capacity];
        t = -1;
    }
    public ArrayStack() { this(CAPACITY); }
    @Override
    public int size() { return (t + 1); }
    @Override
    public boolean isEmpty() { return (t == -1); }
    @Override
    public void push(E e) throws IllegalStateException {
        if (t == data.length - 1) throw new IllegalStateException();
        data[t + 1] = e;
        t++;
    }
    @Override
    public E pop() throws IllegalStateException {
        if (t == -1) return null;
        E temp = data[t];
        data[t] = null;
        t--;
        return temp;
    }
    @Override
    public E top() {
        if (t == -1) return null;
        return data[t];
    }
}