import CursoredLinkedList; import Pair; /** * A simple implementation of dictionaries, using a list of * key/value pairs. * * @author Samuel A. Rebelsky * @author Your Name Here */ public class AssociationList implements Dictionary { // +--------+-------------------------------------------------- // | Fields | // +--------+ /** The pairs in the dictionary. */ private CursoredLinkedList pairs; // +--------------+-------------------------------------------- // | Constructors | // +--------------+ /** Create a new association list. */ public AssociationList() { this.pairs = new CursoredLinkedList(); // Because the find method skips the starting node, // we make sure the association list begins with an // unused pair. It should always have this pair at the // front. pairs.addToFront(new Pair("FRONT","")); } // AssociationList() // +---------+------------------------------------------------- // | Methods | // +---------+ /** * Populate the association list with some sample pairs. * Intended primarily for testing. */ public void populate() { pairs.addToEnd(new Pair("Joshua Vickery", "Undecided")); pairs.addToEnd(new Pair("Sierra Soleil", "Philosophy")); pairs.addToEnd(new Pair("Kate Ducey", "Theatre")); pairs.addToEnd(new Pair("Wanlin Liu", "Economics")); } // populate() /** * Get the value associated with a key. See the interface * for more information. */ public Object get(Object key) throws Exception { try { // Find the first pair with the appropriate key. pairs.front(); pairs.find(new Pair(key, null)); // If we got this far, find succeeded. return ((Pair) pairs.getCurrent()).getValue(); } // Whoops! Not found catch (Exception e) { throw new Exception(key.toString() + " not found"); } } // get(Object) /** * Set the value associated with a particular key. See the * interface for more information. */ public void put(Object key, Object value) throws Exception { // Delete any other pair with that key. try { // Find the first pair with the appropriate key. pairs.front(); pairs.find(new Pair(key, null)); // If we got this far, find succeeded, so delete the // now-useless element. pairs.delete(); } // Whoops! Not found. But we don't care. catch (Exception e) { // Do nothing } // Put a new pair at the end. pairs.addToEnd(new Pair(key,value)); } // put(Object,Object) /** * Convert to a string. */ public String toString() { String result = ""; pairs.front(); try { while (true) { Pair p = (Pair) pairs.getCurrent(); result = result + p + " "; pairs.advance(); } } catch (Exception e) { // Hit the end of the list. } return result; } // toString } // AssociationList