public class ArrayStack<E> {

	private int capacity;                   //stack capacity
	public static final int CAPACITY = 100; //default stack capacity
	private Object[] S;                     //Generic array used to implement the stack
	private int tos = -1;                   //index for the top of stack
	
    public ArrayStack(){this(CAPACITY);}
	
    public ArrayStack(int cap){
	capacity = cap;
	S = new Object [capacity]; 
    }
    //
    // NOTE: java does not allow creation of array with parametrised type!
    //       i.e. java does not allow generic array creation, therefore we cast objects
    //
	
    public int size(){return tos+1;}
	 
    public boolean isEmpty(){return tos == -1;}
	
    public void push(E element) throws StackException {
	if (size() == capacity)
	    throw new StackException("Stack overflow");
	tos++;
	S[tos] = element;
    }
	
    public E top() throws StackException{
	if (isEmpty()) throw new StackException("Stack empty");
	return (E)S[tos];
    }
    //
    // need to cast Object to type E
    //
	
    public E pop() throws StackException {
	if (isEmpty()) throw new StackException("Stack underflow");
	E element = (E)S[tos];
	S[tos] = null;
	tos--;		
	return element;
    }
    //
    // need to cast Object to type E
    //
    
    public String toString(){
	String s = "[";
	if (tos >= 0) s = s + S[0];
	for (int i=1;i<=tos;i++) s = s +","+ S[i];
	return s + "]";
    }
}