Source of 21.5.java


  1: // @author Frank M. Carrano, Timothy M. Henry
  2: // @version 5.0
  3: public V add(K key, V value)
  4: {
  5:    checkIntegrity();
  6:    if ((key == null) || (value == null))
  7:       throw new IllegalArgumentException("Cannot add null to this dictionary.");
  8:    else
  9:    {
 10:       V result = null;
 11:       int keyIndex = locateIndex(key);
 12:       if (keyIndex < numberOfEntries)
 13:       {
 14:          // Key found, return and replace entry's value
 15:          result = dictionary[keyIndex].getValue(); // Get old value
 16:          dictionary[keyIndex].setValue(value);                 // Replace value
 17:       }
 18:       else // Key not found; add new entry to dictionary
 19:       {
 20:          // Add at end of array
 21:          dictionary[numberOfEntries] = new Entry<>(key, value);
 22:          numberOfEntries++;
 23:          ensureCapacity(); // Ensure enough room for next add
 24:       } // end if
 25:       return result;
 26:    } // end if
 27: } // end add

 29: // Returns the array index of the entry that contains key, or
 30: // returns numberOfEntries if no such entry exists.
 31: // Precondition: key is not null.
 32: private int locateIndex(K key)
 33: {
 34:    // Sequential search
 35:    int index = 0;
 36:    while ( (index < numberOfEntries) &&
 37:            !key.equals(dictionary[index].getKey()) )
 38:       index++;
 39:    return index;
 40: } // end locateIndex