// CSE 373, Winter 2013, Marty Stepp // This class defines an implementation of the stack ADT using an array // as the internal data structure. import java.util.Arrays; import java.util.EmptyStackException; public class ArrayStack implements Stack { private E[] elements; private int size; // Constructs a new empty stack. public ArrayStack() { elements = (E[]) (new Object[5]); size = 0; } // Adds the given value to the top of this stack. public void push(E value) { if (size == elements.length) { // copy into an array twice as large elements = Arrays.copyOf(elements, 2 * size); } elements[size] = value; size++; } // Removes and returns the top element of this stack. // Throws an EmptyStackException if the stack is empty. public E pop() { if (size == 0) { throw new EmptyStackException(); } E top = elements[size - 1]; elements[size - 1] = null; size--; return top; } // Returns the top element of this stack without removing it. // Throws an EmptyStackException if the stack is empty. public E peek() { if (size == 0) { throw new EmptyStackException(); } return elements[size - 1]; } // Returns true if the stack does not contain any elements. public boolean isEmpty() { return (size == 0); } // Returns the number of elements contained in this stack. public int size() { return size; } }