//stack implementation using array //Author: Konstantin Voevodski //Date: 6/4/07 public class myArrayStack { private static final int DEFAULT_CAPACITY = 10; private int size; private AnyType[] items; //constructor just creates an empty stack public myArrayStack () { size = 0; items = (AnyType[]) new Object[DEFAULT_CAPACITY]; } public boolean isEmpty () { return (size == 0); } //insert item in the back of the array, increase size of array if necessary public void push (AnyType value) { if(items.length == size) { ensureCapacity(size * 2 + 1); } items[size++] = value; //note the postfix use of the ++ operator, it is incremented AFTER it is used } //remove item from the back of the array public AnyType pop () { if(isEmpty()) { throw new java.util.NoSuchElementException(); } return(items[--size]); //note the prefix use of the ++ operator, it is incremented BEFORE it is used } public void ensureCapacity(int newCapacity) //increase the size of the array { AnyType[] old = items; items = (AnyType[]) new Object[newCapacity]; //create a new array to hold the items and copy them over for(int x = 0; x < size; x++) { items[x] = old[x]; } } }