/** * Collections of elements not supporting iteration. The technique used * for implementation is to put the elements in an array, adding new elements * at the end of the array and removing elements from the end of the array. */ public class ArrayBasedStack implements Stack { // +--------+-------------------------------------------------- // | Fields | // +--------+ /** The elements of the stack. */ protected Object[] elements; /** * The number of elements in the stack. The top of the stack is * always at index size-1. */ protected int size; // +--------------+-------------------------------------------- // | Constructors | // +--------------+ /** * Build a new stack with a specified capacity. */ public ArrayBasedStack(int capacity) { elements = new Object[capacity]; size = 0; } // ArrayBasedStack(int) /** * Build a new stack of default capacity. (Not generally a good idea * unless your stack won't be very large.) */ public ArrayBasedStack() { elements = new Object[10]; size = 0; } // ArrayBasedStack() // +-----------+----------------------------------------------- // | Accessors | // +-----------+ /** * Determine if the stack is full (in which case no more * elements can be added). * Precondition: The stack is initialized. */ public boolean isFull() { return size == elements.length; } // isFull() /** * Determine if the stack is empty (in which case no elements * can be deleted). * Precondition: The stack is initialized. * Postcondition: Returns true if the stack is empty, and * false otherwise. */ public boolean isEmpty() { return size == 0; } // isEmpty() /** * Get the top of the stack. * Precondition: The stack is initialized and nonempty. * Postcondition: Returns the top of the stack. */ public Object next() { return elements[size-1]; } // next() // +-----------+----------------------------------------------- // | Modifiers | // +-----------+ /** * Add an element to the top of the stack. * Precondition: The stack is initialized and is not full. * Postcondition: The element is added to the top of the stack. * Postcondition: The stack grows by one element. */ public void add(Object elt) { elements[size] = elt; size = size + 1; } // add(Object) /** * Delete the top from the stack. * Precondition: The stack is initialized and nonempty. * Postcondition: The top element is deleted from the stack. * Postcondition: Returns the element deleted. * Postcondition: The stack shrinks by one element. */ public Object delete() { size = size - 1; return elements[size]; } // delete() } // class ArrayBasedStack