Source of 22.14.java


  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 oldValue;                // Value to return
  9: 
 10:       int index = getHashIndex(key);
 11:       index = probe(index, key); // Check for and resolve collision
 12: 
 13:       // Assertion: index is within legal range for hashTable
 14:       assert (index >= 0) && (index < hashTable.length);
 15: 
 16:       if ( (hashTable[index] == null) || hashTable[index].isRemoved())
 17:       { // Key not found, so insert new entry
 18:          hashTable[index] = new TableEntry<>(key, value);
 19:          numberOfEntries++;
 20:          oldValue = null;
 21:       }
 22:       else
 23:       { // Key found; get old value for return and then replace it
 24:          oldValue = hashTable[index].getValue();
 25:          hashTable[index].setValue(value);
 26:       } // end if
 27: 
 28:       // Ensure that hash table is large enough for another add
 29:       if (isHashTableTooFull())
 30:          enlargeHashTable();
 31: 
 32:       return oldValue;
 33:    } // end if
 34: } // end add
 35: // Version 4.0