package username.dict; import java.io.PrintWriter; import java.util.ArrayList; /** * An implementation of type-specific dictionaries that * uses a pair of parallel arrays. * * @author Samuel A. Rebelsky * @version 1.0 of April 2005 */ public class ArrayBasedNewDict implements NewDict { // +----------------------+------------------------------------ // | Implementation Notes | // +----------------------+ /* (1) We use a pair of parallel arrays, indices and values. For each (index,value) pair, if the index is at position i in the first array, then the value is at position i in the second array. (2) We use "len" to keep track of how many (index,value) pairs are in the array. len should always be <= values.length. (3) The arrays should expand when a value gets added. Right now, that expansion is not supported. */ // +--------+-------------------------------------------------- // | Fields | // +--------+ /** All of the indices, in no particular order. */ I[] indices; /** All of the values, in the same order as the indices. */ V[] values; /** How many values are stored in the dict. */ int len; // +--------------+-------------------------------------------- // | Constructors | // +--------------+ /** * Create a new array-based dictionary. */ public ArrayBasedNewDict() { this.indices = (I[]) new Object[16]; this.values = (V[]) new Object[16]; this.len = 0; } // ArrayBasedNewDict() // +--------------------+-------------------------------------- // | Dictionary Methods | // +--------------------+ public void put(I index, V value) { // See if it's already there. try { int i = this.find(index); // If so, update the corresponding value this.values[i] = value; } // If it's not there, add it catch (Exception e) { // Make sure there's enough room if (this.len >= this.values.length) { // STUB } // if there's not enough room else { this.indices[this.len] = index; this.values[this.len] = value; this.len++; } // if } // catch } // put(I, V) public V get(I index) { // Use the helper method to find the integer index try { return this.values[this.find(index)]; } // If that failed, return the default value catch (Exception e) { return null; } // catch(Exception) } // get(I) public void dump(PrintWriter pen) { for (int i = 0; i < this.len; i++) pen.println(this.indices[i] + " => " + this.values[i]); } // dump(PrintWriter) // +---------------+------------------------------------------- // | Local Helpers | // +---------------+ /** * Find the position in the array of an index. If the * value is not there, throw an exception. */ int find(I index) throws Exception { // Look at each position in turn for (int i = 0; i < this.len; i++) { // If the index matches if (this.indices[i].equals(index)) { // Return the position return i; } // if } // for // If we've reached this point, it's not there throw new Exception("Cannot find '" + index + "'"); } // find(I) } // ArrayBasedNewDict