package username.linear; /** * Part of an array-based implementation of stacks. * * @author Samuel A. Rebelsky * @author Your Name Here * @version 0.6 of March 2006 */ // +-------+------------------------------------------------------------- // | Notes | // +-------+ /* We use an array to store the values in the stack. The initial element to get added gets put in index 0, the next element goes in index 1, and so on and so forth. An integer, size, keeps track of the next location to which we'll add a value. */ public class ArrayBasedStack implements Stack { // +--------+------------------------------------------------------------ // | Fields | // +--------+ /** The array that stores the values. */ Object[] stuff; /** The place in which the next value goes. */ int size; // +-------------+------------------------------------------------------- // | Construtors | // +-------------+ /** * Build a new stack. */ public ArrayBasedStack() { // Use an array of size 10. this.stuff = new Object[10]; // The stack is empty, so the next element goes at 0. this.size = 0; } // ArrayBasedStack() // +---------+----------------------------------------------------------- // | Methods | // +---------+ /** * Add an element to the stack. * * @param val * The object that is to be added. * @post * The stack now contains an additional copy of val. */ public void put(T val) { this.stuff[this.size] = val; ++this.size; } // put(T) /** * Remove the most-recently-added element that is still in the * stack. * * @return val * An object in the structure. * @pre * The structure is not empty. * @post * The structure contains one fewer copy of val. * @post * Every value in the stack was added less recently than val. */ @SuppressWarnings({"unchecked"}) public T get() { --this.size; // Remember the element we're about to return. Object returnme = this.stuff[this.size]; // For safety, we clean out that part of the array. this.stuff[this.size] = null; return (T) returnme; } // get() /** * Determine which object will next be returned by get. * * @return val * An object in the stack * @pre * The structure is not empty. * @post * Every other value in the stack was added less recently than val. */ @SuppressWarnings({"unchecked"}) public T peek() { return (T) this.stuff[this.size - 1]; } // peek() /** * Determine if the stack is empty. */ public boolean isEmpty() { return (this.size == 0); } // isEmpty() } // class ArrayBasedStack