Hello, can somebody explain to me why this block of code doesn’t work?
ArrayList<Object> list = new ArrayList<Object>();
list.add(list);
HashMap<Object, Integer> map = new HashMap<Object, Integer>();
map.put(list, 1);
After I put list to map, it throws StackOverFlowError.
I know this code doesn’t make any sense, I just want to know why it’s not working.
Thanks!
Edit:
stacktrace:
Exception in thread "main" java.lang.StackOverflowError
at java.util.ArrayList.get(Unknown Source)
at java.util.AbstractList$Itr.next(Unknown Source)
at java.util.AbstractList.hashCode(Unknown Source)
at java.util.AbstractList.hashCode(Unknown Source)
...
It happens because you are trying to calculate hash of an
ArrayListwhich contains itself.ArrayListcalculates its own hash by calculating hashes of all the objects it references. As it references itself, it will try to calculate its own hash over and over again causing the stack overflow.