Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is hashcode calculated for null object

Tags:

java

Since HashMap and HashSet allows null objects, what would be the hash value of these 'null' objects? How it is being calculated/handled in java?

like image 658
Sivasubramaniam Arunachalam Avatar asked Feb 21 '23 01:02

Sivasubramaniam Arunachalam


2 Answers

The HashMap built into openJDK just puts the null reference into the first bucket in the array that it uses to hold entries

409     private V putForNullKey(V value) {
410         for (Entry<K,V> e = table[0]; e != null; e = e.next) {
411             if (e.key == null) {
412                 V oldValue = e.value;
413                 e.value = value;
414                 e.recordAccess(this);
415                 return oldValue;
416             }
417         }
418         modCount++;
419         addEntry(0, null, value, 0);
420         return null;
421     }
like image 198
Affe Avatar answered Feb 22 '23 14:02

Affe


For HashMap for example, it is just a special case. See the source code below that I have taken from JDK 1.6:

public V put(K key, V value) {
    if (key == null)
        return putForNullKey(value);
    int hash = hash(key.hashCode());
    ...

}

/**
 * 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 44
hage Avatar answered Feb 22 '23 14:02

hage