Show Stopper Show Stopper - 5 months ago 17
Java Question

Infinite loop when using a key multiple times in HashMap

HashMap
falls into an infinite loop.

I am not able to understand why
HashMap
throws stackoverflow error when the same key is used multiple times.

Code:

import java.util.HashMap;

public class Test {
public static void main(String[] args) {
HashMap hm = new HashMap();

hm.put(hm, "1");
hm.put(hm, "2");
}
}


Error:


Exception in thread "main" java.lang.StackOverflowError

Answer

It is not possible to add to a Map itself as a key. From javadoc:

A special case of this prohibition is that it is not permissible for a map to contain itself as a key.


The problem is that you are using as key not a standard object (any object with well defined equals and hashCode methods, that is not the map itself), but the map itself.

The problem is on how the hashCode of the HashMap is calculated:

public int hashCode() {
   int h = 0;
   Iterator<Entry<K,V>> i = entrySet().iterator();
   while (i.hasNext())
       h += i.next().hashCode();
   return h;
}

As you can see, to calculate the hashCode of the map, it iterates over all the elements of the map. And for each element, it calculates the hashCode. Because the only element of the map has as key is the map itself, it becomes a source of recursion.

Replacing the map with another object that can be used as key (with well defined equals and hashCode) will work:

import java.util.HashMap;

 public class Test {
   public static void main(String[] args) {
     HashMap hm = new HashMap();

     String key = "k1";
     hm.put(key, "1");
     hm.put(key, "2");
   }
}