Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java StackOverflowError after putting ArrayList to HashMap

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)
    ...
like image 819
peto1234 Avatar asked Apr 22 '12 09:04

peto1234


2 Answers

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.

like image 84
Malcolm Avatar answered Oct 24 '22 01:10

Malcolm


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

like image 22
Thomas Uhrig Avatar answered Oct 24 '22 00:10

Thomas Uhrig