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 ArrayList
which contains itself. ArrayList
calculates 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.
First of all: I am not sure. But as far as I know, will HashMap ask the key (in your case the list) for its HashCode. HashMap stores this HashCode in a table to find the elements faster. That's why it is called HashMap. When the List is asked for its HashCode, it will try to calculate it. And I think here is the problem. To calculate the HashCode, the list will ask every contained element for its HashCode. And this is the point where you get the stackoverflow.
1) Take a look at the put method of HashMap:
http://www.docjar.com/html/api/java/util/HashMap.java.html
2) Then take a look at the hashCode() method of AbstractList (the super class of ArrayList):
http://www.docjar.com/html/api/java/util/AbstractList.java.html
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