Sunday, 24 April 2016

How null key is handled in HashMap ?


equals()
 and hashCode() are used to store and retrieve values, but null is handled in different way using 2 different methods : 
  1. putForNullKey(V value)
  2. getForNullKey()

Null keys always map to index 0.


Internal implementation
private getForNullKey() {
   for (Entry<K,V> e = table[0]; e != null; e = e.next) {
      if (e.key == null)
         return e.value;
   }
   return null;
}
/**
 * Offloaded version of put for null keys
 */
private 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;

}

No comments:

Post a Comment

Note: only a member of this blog may post a comment.