package username.dict; import java.io.PrintWriter; import java.util.Vector; /** * An implementation of type-specific dictionaries that a vector * of key/value pairs. * * @author Samuel A. Rebelsky * @version 2.0 of November 2005 */ public class VectorBasedDict implements Dict { // +----------------------+------------------------------------ // | Implementation Notes | // +----------------------+ /* (1) We use a Vector of KeyedValues. If the key of the KeyedValue matches the desired value, we return the corresponding value in the pair. (2) We use "len" to keep track of how many (key,value) pairs are in the vector. */ // +--------+-------------------------------------------------- // | Fields | // +--------+ /** All of the key/value pairs, in no particular order. */ Vector> pairs; /** How many values are stored in the dictionary. */ int len; // +--------------+-------------------------------------------- // | Constructors | // +--------------+ /** * Create a new vector-based dictionary. */ public VectorBasedDict() { this.pairs = new Vector>(); this.len = 0; } // VectorBasedDict() // +--------------------+-------------------------------------- // | Dictionary Methods | // +--------------------+ public void put(K key, V value) { this.pairs.add(new KeyedValue(key, value)); ++this.len; } // put(K, V) public V get(K key) throws NoSuchKeyException { // Use the helper method to find the integer index. try { return this.pairs.get(this.find(key)).value; } // If that failed, return the default value catch (Exception e) { throw new NoSuchKeyException(key.toString()); } // catch(Exception) } // get(K) public void dump(PrintWriter pen) { for (int i = 0; i < this.len; i++) { pen.println(this.pairs.get(i)); } // for } // dump(PrintWriter) // +---------------+------------------------------------------- // | Local Helpers | // +---------------+ /** * Find the position in the array of a key. If the * value is not there, throw an exception. */ int find(K key) throws Exception { // Look at each position in turn for (int i = 0; i < this.len; i++) { // If the key matches if (this.pairs.get(i).key.equals(key)) { // Return the position return i; } // if } // for // If we've reached this point, it's not there throw new Exception("Cannot find '" + key + "'"); } // find(K) } // VectorBasedDict