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?
Asked
Active
Viewed 2,003 times
4
-
1It's implementation specific - either throw NPE or use `hashCode = 0` – Bohemian Jun 25 '12 at 05:52
2 Answers
6
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 }

Affe
- 47,174
- 11
- 83
- 83
2
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;
}

hage
- 5,966
- 3
- 32
- 42