你能解释下面的情景吗?
HashMap<HashMap,HashMap> hm=new HashMap<>();
hm.put(hm,hm);
hm.get(hm); // ----> On commenting this line, I get no error.
// If I uncomment it, I am getting StackOverflowError
试图把HashMap
作为一个关键内部是一个坏主意。
在hm.put(hm,hm)
之后,你的HashMap
包含一个密钥,其hashCode()
是hm.hashCode()
。 hm.hashCode()
是所有hashCode()
条目的Map
的函数。条目的hashCode()
是密钥和值的hashCode()
的函数(在你的情况下都是hm
)。因此,为了计算hm.hashCode()
,你必须计算hm.hashCode()
。这导致无限递归。
调用hm.get(hm);
需要计算hm.hashCode()
,导致无限递归和StackOverflowError
。