1: public V add(K key, V value) 2: { 3: checkInitialization(); 4: if ((key == null) || (value == null)) 5: throw new IllegalArgumentException("Cannot add null to a dictionary."); 6: else 7: { 8: V result = null; 9: int keyIndex = locateIndex(key); 10: if (keyIndex < numberOfEntries) 11: { 12: // Key found, return and replace entry's value 13: result = dictionary[keyIndex].getValue(); // Get old value 14: dictionary[keyIndex].setValue(value); // Replace value 15: } 16: else // Key not found; add new entry to dictionary 17: { 18: // Add at end of array 19: dictionary[numberOfEntries] = new Entry<>(key, value); 20: numberOfEntries++; 21: ensureCapacity(); // Ensure enough room for next add 22: } // end if 23: return result; 24: } // end if 25: } // end add 26: 27: // Returns the array index of the entry that contains key, or 28: // returns numberOfEntries if no such entry exists. 29: private int locateIndex(K key) 30: { 31: // Sequential search 32: int index = 0; 33: while ( (index < numberOfEntries) && !key.equals(dictionary[index].getKey()) ) 34: index++; 35: return index; 36: } // end locateIndex 37: // Version 4.0