StackOverflowError on HashMap.hashCode() due to self reference

Vitaly Davidovich vitalyd at gmail.com
Fri Jul 17 18:58:15 UTC 2015


IMHO, this doesn't warrant any special wording -- if someone hits this, I
think it's fairly evident what the issue is.  You can get the same problem
with adding an ArrayList to itself and calling hashCode().

On Fri, Jul 17, 2015 at 2:45 PM, Krystal Mok <rednaxelafx at gmail.com> wrote:

> Hi everyone,
>
> I'm sure somebody has seen this stack overflow before. My question is: is
> it expected (which should be documented to warn people not to do this), or
> is it considered a bug (which should be fixed)?
>
> Example:
> https://gist.github.com/rednaxelafx/930f8979473185cfc0a0
>
> import java.util.*;
>
> public class HashMapStackOverflow {
>   public static void main(String[] args) throws Exception {
>     HashMap<String, Object> map = new HashMap<>();
>     map.put("self", map);
>     System.out.println(map.hashCode());
>   }
> }
>
> $ ~/sdk/jdk1.8.0/Contents/Home/bin/java HashMapStackOverflow
> Exception in thread "main" java.lang.StackOverflowError
> at java.util.AbstractMap.hashCode(AbstractMap.java:505)
> at java.util.Objects.hashCode(Objects.java:98)
> at java.util.HashMap$Node.hashCode(HashMap.java:296)
> at java.util.AbstractMap.hashCode(AbstractMap.java:507)
> at java.util.Objects.hashCode(Objects.java:98)
> at java.util.HashMap$Node.hashCode(HashMap.java:296)
> at java.util.AbstractMap.hashCode(AbstractMap.java:507)
> at java.util.Objects.hashCode(Objects.java:98)
> at java.util.HashMap$Node.hashCode(HashMap.java:296)
> at java.util.AbstractMap.hashCode(AbstractMap.java:507)
> ...
>
> This will cause a stack overflow because HashMap.hashCode() is inherited
> from AbstractMap, which sums the hash code of each entry, while one of the
> entries is itself so it goes recursive.
>
> Thanks,
> Kris
>



More information about the core-libs-dev mailing list