import java.util.EmptyStackException; /** Implementation of the StackInt interface using an array. @author Koffman and Wolfgang */ public class ArrayStack { // Data Fields /** Storage for stack. */ Object[] theData; /** Index to top of stack. */ int topOfStack = -1; // Initially empty stack public ArrayStack() { theData = new Object[10]; } public Object push(Object item) { if (topOfStack == theData.length - 1) { reallocate(); } topOfStack++; theData[topOfStack] = item; return item; } /** Remove and return the top item on the stack. pre: The stack is not empty. post: The top item on the stack has been removed and the stack is one item smaller. @return The top item on the stack @throws EmptyStackException if the stack is empty */ public Object pop() { if (empty()) { throw new EmptyStackException(); } return theData[topOfStack--]; } /** Return the top item on the stack Pre: The stack is not empty Post: The stack remains unchanged @return The top item on the stack @throws EmptyStackException If the stack is empty */ public Object peek() { if (empty()) { throw new EmptyStackException(); } return theData[topOfStack]; } /** Return true if the stack is empty @return True if the stack is empty */ public boolean empty() { return topOfStack == -1; } /** Method to reallocate the array containing the stack data Postcondition: The size of the data array has been doubled and all of the data has been copied to the new array */ private void reallocate() { Object[] temp = new Object[2 * theData.length]; System.arraycopy(theData, 0, temp, 0, theData.length); theData = temp; } }