Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hashcode for NULL key in HashMap

I was just reading about the difference between HashMap and HashTable class in java. There I found a difference that former allow null key and later doesn't privileges for the same. As far as the working of HashMap is concern I know that, it calls hashcode method on key for finding the bucket in which that key value pair is to be placed. Here comes my question: How hashcode for a null value is computed or Is there any default value for hashcode of null key (if so please specify the value)?

like image 263
Prashant Avatar asked Jun 24 '13 04:06

Prashant


2 Answers

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

like image 81
radai Avatar answered Oct 06 '22 23:10

radai


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;
}
like image 45
Shiva Kumar Avatar answered Oct 07 '22 00:10

Shiva Kumar