public class ArrayMap implements Dictionary { // Make Entry an inner class of Dictionary private class Entry { private K key; // Key private V value; // Value public Entry(K k, V v) // Constructor { key = k; value = v; } /** Accessor method for the key */ public K getKey() {return key;} /** Accessor method for the value */ public V getValue() {return value;} /** Mutator method for the value */ public void setValue(V v) {value = v;} public String toString() { return "(" + key + "," + value + ")"; } } Entry[] entry; // Dictionary int nEntries; // # Entries in dictionary public ArrayMap(int N) // Constructor { entry = new Entry[N]; nEntries = 0; } public int size() { return nEntries; } /* ------------------------------------------------------ put(k,v): if key k found: update corresponding value otherwise: insert (k,v) ------------------------------------------------------ */ public void put(K k, V v) { for (int i = 0; i < nEntries; i++) if ( entry[i].getKey().equals(k) ) { entry[i].setValue(v); // Found key k --> update value return; } // Key not found --> insert (K,V) entry[nEntries] = new Entry(k,v); nEntries++; } /* ------------------------------------------------------ get(k): if key k found, return corresponding value otherwise: return null ------------------------------------------------------ */ public V get(K k) { for (int i = 0; i < nEntries; i++) if ( entry[i].getKey().equals(k) ) return entry[i].getValue(); return null; } /* ---------------------------------------------------------------- remove(k): if key k found, remove Entry with k and return value otherwise: do nothing and return null ------------------------------------------------------ */ public V remove(K k) { boolean found = false; // Found int loc = -1; // Location of key k V ret = null; // Return value for (int i = 0; i < nEntries; i++) if ( entry[i].getKey().equals(k) ) { found = true; loc = i; break; } if ( found ) { ret = entry[loc].getValue(); // Save return value for ( int i = loc+1; i < nEntries; i++ ) entry[i-1] = entry[i]; // Shift array nEntries--; } return ret; } public String toString() { String s = ""; for (int i = 0; i < nEntries; i++) s += "["+i+"]: " + entry[i].toString() + "\n"; return s; } }