// A generic Dictionary class which maps keys to values. import java.util.*; public class Dictionary { private ArrayList> entries; // Another solution would be to use two ArrayLists, one holding // keys and one holding values. However, this solution is // cleaner: it makes explicit the fact that the keys and values // are associated. With two ArrayLists, the fact that they go // together exists only in the mind of the programmer, and we // would have to be very careful not to let the two lists get out // of sync. For example, inserting a key into the middle of the // first list and forgetting to insert a value in the // corresponding place in the second list would wreak havoc (all // the following keys would suddenly correspond to different // values, and the last key wouldn't correspond to any value at // all)! With this solution, that can't happen. public Dictionary() { entries = new ArrayList>(); } public void add(K key, V value) { // look for the key and update the value if it already exists. for (Pair p : entries) { if (p.getFirst().equals(key)) { p.setSecond(value); return; } } // didn't find the key, so add a new pair. entries.add(new Pair(key, value)); } public V lookup(K key) { for (Pair p : entries) { if (p.getFirst().equals(key)) { return p.getSecond(); } } // One might wonder whether we could use the indexOf method of // ArrayList instead of using an explicit for loop to search // the entries list. We could --- but only if we overrode the // equals method of Pair to only look at the first component // and ignore the second. This is left as an exercise for the // reader. =) return null; } public void remove(K key) { // Since we want to remove something, we can't use a foreach // loop; we have to use an explicit iterator. for (Iterator> it = entries.iterator(); it.hasNext();) { if (it.next().getFirst().equals(key)) { it.remove(); return; } } } }