Where is key stored for null in HashMap of Java

  • 2021-08-12 02:38:17
  • OfStack

We know that the HashMap collection is allowed to store null values

hashMap is based on hashCode of key to find the storage location, so when key is null, how to store it?

In the put method, line 1 actually deals with the case of key=null.


// HashMap Adj. put Method 
 public V put(K key, V value) {
    if (table == EMPTY_TABLE) {
      inflateTable(threshold);
    }
    if (key == null)
       // key For null Call putForNullKey(value)
       return putForNullKey(value);
    int hash = hash(key);
    int i = indexFor(hash, table.length);
    for (Entry<K,V> e = table[i]; e != null; e = e.next) {
      Object k;
      if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
        V oldValue = e.value;
        e.value = value;
        e.recordAccess(this);
        return oldValue;
      }
    }
 
    modCount++;
    addEntry(hash, key, value, i);
    return null;
  }

 /**
   * Offloaded version of put for null keys
   */
  private V putForNullKey(V value) {
    for (Entry<K,V> e = table[0]; e != null; e = e.next) {
      if (e.key == null) {
        V oldValue = e.value;
        e.value = value;
        e.recordAccess(this);
        return oldValue;
      }
    }
    modCount++;
    addEntry(0, null, value, 0);
    return null;
  }

When the put method of HashMap, the second judgment is that key is null, and then the method of putForNullKey (V value) is entered

As you can see, the previous for loop looks up the element where key is null in the talbe [0] linked list. If it is found, value is re-assigned to value of this element and the original value is returned.

If the for loop above is not found, add this element to the header of the talbe [0] linked list.


Related articles: