package stacks; public class ArrayStack implements Stack{ private int capacity; //The actual capacity of the stack array public static final int CAPACITY = 100; //default array capacity private E s[]; //Generic array used to implement the stack private int top = -1; //index for the top of the stack public ArrayStack(){ this(CAPACITY); } public ArrayStack(int cap){ capacity=cap; s=(E[]) new Object[capacity];//compiler may give a warning, but this is ok //Used instead of S=new E[cap];Since can't create a new array using parameterised type } public int size(){ return (top+1); } public boolean isEmpty(){ return (top<0); } public void push(E element) throws FullStackException { if (size()==capacity) throw new FullStackException("Stack is full."); s[++top]=element; } public E top() throws EmptyStackException{ if (isEmpty()) throw new EmptyStackException("Stack is empty."); return s[top]; } public E pop() throws EmptyStackException { E element; if (isEmpty()) throw new EmptyStackException("Stack is empty"); element = s[top]; s[top--]=null; //dereference S[top] for garbage collection return element; } public String toString(){ String st; st="["; if (size()>0) st+=s[0]; if (size()>1) for (int i=1;i<=size()-1;i++){ st+=","+s[i]; } return st + "]"; } // Prints status information about a recent operation and the stack public void status(String op, Object element){ System.out.print("------> " + op); //print this operation System.out.println(", returns " + element); //what was returned System.out.print("result: size = " + size() + ", isEmpty= " +isEmpty()); System.out.println(", stack: " + this); //contents of the stack } }