Hashcode for NULL key in HashMap
From the source code of HashMap, if the key is null
it is handled differently. There is no hashcode generated for null, but it is uniquely stored at index 0 in an internal array with hash value 0. Also note that hash value of an empty string also is 0(in case keys are strings), but the index where it is stored in the internal array ensures that they are not mixed up.
/**
* 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;
}
from HashMap:
public V put(K key, V value) {
if (key == null)
return putForNullKey(value);
...
and if you look further you will see that null always goes to bin 0
If you read description of static int hash(int h)
method in HashMap you will find that null keys have index 0.