Java StackOverflowError after placing ArrayList in HashMap

Hello, can someone explain to me why this block of code is not working?

ArrayList<Object> list = new ArrayList<Object>();
list.add(list);

HashMap<Object, Integer> map = new HashMap<Object, Integer>();
map.put(list, 1);

After I put the list on the map, it throws a StackOverFlowError.

I know this code doesn't make any sense, I just want to know why it doesn't work.

Thank!

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)
    ...
+5
source share
2 answers

This is because you are trying to compute a hash ArrayListthat contains itself. ArrayListcalculates its own hash, calculating the hashes of all the objects that it refers to. Since it refers to itself, it will try to compute its own hash again and again, causing a stack overflow.

+13
source

: . , , HashMap ( ) HashCode. HashMap HashCode , . HashMap. List HashCode, . , . HashCode, HashCode. , stackoverflow.

1) put HashMap:

http://www.docjar.com/html/api/java/util/HashMap.java.html

2) hashCode() AbstractList ( ArrayList):

http://www.docjar.com/html/api/java/util/AbstractList.java.html

+1

All Articles