public class DynamicArrayStack implements Stack { // Constants private static final int MIN_CAPACITY = 100; private static final double GROWTH_FACTOR = 1.5; // Instance variables private E[] elems; private int top = -1; // designates the top element or -1 if empty @SuppressWarnings( "unchecked" ) public DynamicArrayStack() { // pre-condictions: elems = (E[]) new Object[ MIN_CAPACITY ]; } // Returns true if this stack is empty; public boolean isEmpty() { return top == -1; } // Returns the top element of this stack without removing it. public E peek() { // pre-conditions: ! isEmpty() return elems[ top ]; } // Returns and remove the top element of this stack. public E pop() { // pre-conditions: ! isEmpty() // save the top element E saved = elems[ top ]; // scrub the memory, then decrements top elems[ top-- ] = null; return saved; } // Puts the element onto the top of this stack. public void push( E element ) { if ( top == ( elems.length - 1 ) ) { increaseSize(); } // increments top, stores the element at position top elems[ ++top ] = element; } @SuppressWarnings( "unchecked" ) private void increaseSize() { E[] newElems; int newSize = (int) ( elems.length * GROWTH_FACTOR ); newElems = (E[]) new Object[ newSize ]; System.arraycopy( elems, 0, newElems, 0, elems.length ); // Replacing elems with the new/larger array elems = newElems; } }