Source of 21.11.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);

 13:       if ( (keyIndex < numberOfEntries) &&
 14:             key.equals(dictionary[keyIndex].getKey()) )
 15:       {
 16:          // Key found, return and replace entry's value
 17:          result = dictionary[keyIndex].getValue(); // Get old value
 18:          dictionary[keyIndex].setValue(value);     // Replace value
 19:       }
 20:       else // Key not found; add new entry to dictionary
 21:       {
 22:          makeRoom(keyIndex); // Make room for new entry
 23:          dictionary[keyIndex] = new Entry<>(key, value); // Insert new entry in array
 24:          numberOfEntries++;
 25:          ensureCapacity(); // Ensure enough room for next add
 26:       } // end if

 28:       return result;
 29:    } // end if
 30: } // end add