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?
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 }
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With