import java.util.Vector; /** * An implementation of stacks that uses vectors. * * @author Samuel A. Rebelsky */ public class VectorBasedStack implements Stack { // +-------+--------------------------------------------------- // | Notes | // +-------+ // +-----------+----------------------------------------------- // | Constants | // +-----------+ // +--------+-------------------------------------------------- // | Fields | // +--------+ /** * The actual contents of the list, stored in a Vector. */ Vector contents; // +--------------+-------------------------------------------- // | Constructors | // +--------------+ /** * Build an empty list. */ public VectorBasedStack() { this.contents = new Vector(); } // VectorBasedStack() // +------------------+---------------------------------------- // | Exported Methods | // +------------------+ /** * Determine if the stack is empty */ public boolean isEmpty() { return this.contents.isEmpty(); } // isEmpty() /** * Add an element to the stack. */ public void add(Object newThingy) { this.contents.add(newThingy); } // add(Object) /** * Update the list by removing the last element in the vector. Return * that element. */ public Object get() { return this.contents.remove(last()); } // get() public Object peek() { return this.contents.get(last()); } // peek() // Find the position of the last element in the vector private int last(){ if (this.contents.size() >= 1) return (this.contents.size() - 1); return (this.contents.size() - 1); }//last() /** * Get the length. */ public int length() { return this.contents.size(); } // length() /** * Convert to a string for ease of printing. */ public String toString() { if (this.contents.isEmpty()) return "()"; String result = "(" + this.contents.get(last()); for (int i = last()-1; i >= 0; i--) result = result + " " + this.contents.get(i); result = result + ")"; return result; } // toString() } // class VectorBasedStack