public class ArrayStack implements Stack {

    private Object[] objects;
    private int top; // id's next available slot

    public ArrayStack() {
        this.objects = new Object[16];
        this.top = 0; 
    }

	public int size() {
	    return this.top;
	}
	
	public boolean isEmpty() {
	    return this.top == 0;
	}
	
	public Object peek() throws EmptyStackException {
        if (this.top == 0)
            throw new EmptyStackException();
        return this.objects[top-1];
	}
	
	public void push(Object o) {
        if (this.top == this.objects.length) {
            Object[] newarray = new Object[this.objects.length*2];
            for (int i = 0; i < this.objects.length; i++)
                newarray[i] = this.objects[i];
            this.objects = newarray;
        }
        this.objects[this.top] = o;
        this.top++;
	}

	public Object pop() throws EmptyStackException {
        if (this.top == 0)
            throw new EmptyStackException();
        Object obj = this.objects[top-1];
        this.objects[top-1] = null;
        this.top--;
        return obj;
	}
	
	public static void main( String[] args ) {
        ArrayStack s = new ArrayStack();
        s.push( 4 );
        s.push( 5 );
        try {
            Object obj = s.pop();
            System.out.println( "popped " + obj );
            System.out.println( "peek " + s.peek() );
            s.pop();
            System.out.println( "peek " + s.peek() );
        }
        catch (EmptyStackException e) {
            System.out.println( "but it was empty" );
        }
	}
}
