Search code examples
javahashmapstack-overflow

HashMap get method throwing error on hm.get(hm)


Could you please explain the below scenarios?

HashMap<HashMap,HashMap> hm=new HashMap<>();
hm.put(hm,hm);
hm.get(hm); // ----> On commenting this line, I get no error. 
            //       If I uncomment it, I am getting StackOverflowError

Solution

  • Trying to put a HashMap as a key inside itself is a bad idea.

    After hm.put(hm,hm), your HashMap contains a key whose hashCode() is hm.hashCode(). hm.hashCode() is a function of the hashCode() of all the Map's entries. The hashCode() of an entry is a function of the hashCode() of the key and value (both are hm in your case). Hence, in order to compute hm.hashCode(), you have to compute hm.hashCode(). This results in infinite recursion.

    Calling hm.get(hm); required computing hm.hashCode(), leading to infinite recursion and StackOverflowError.