HashMap StackOverflow error when it refer back to itself

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());
  }
}
AbstractMap.hashCode is as below, it will sum up all the hash code for all the entry.

public
int hashCode() { int h = 0; Iterator<Entry<K,V>> i = entrySet().iterator(); while (i.hasNext()) h += i.next().hashCode(); return h; } the hash map entry will be calculate the key and value hash code.

Entry.hashCode
public final int hashCode() { return Objects.hashCode(getKey()) ^ Objects.hashCode(getValue()); }


when compile the hash code for the value which exactly is the map itself. then the infinite cycle is happen.
Objects.hashCode
public static int hashCode(Object o) { return o != null ? o.hashCode() : 0; }
Exception in thread "main" java.lang.StackOverflowError
at java.util.HashMap$Entry.hashCode(HashMap.java:847) at java.util.AbstractMap.hashCode(AbstractMap.java:494) at java.util.Objects.hashCode(Objects.java:96) at java.util.HashMap$Entry.hashCode(HashMap.java:847) at java.util.AbstractMap.hashCode(AbstractMap.java:494) at java.util.Objects.hashCode(Objects.java:96) at java.util.HashMap$Entry.hashCode(HashMap.java:847) at java.util.AbstractMap.hashCode(AbstractMap.java:494) at java.util.Objects.hashCode(Objects.java:96)

 

posted @ 2016-03-07 14:17  princessd8251  阅读(299)  评论(0)    收藏  举报