HashMap get 方法在 hm.get(hm) 上抛出错误
HashMap get method throwing error on hm.get(hm)
能否请您解释一下以下场景?
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 WhosebugError
尝试将 HashMap
作为键放在自身内部是个坏主意。
在 hm.put(hm,hm)
之后,您的 HashMap
包含一个 hashCode()
为 hm.hashCode()
的键。 hm.hashCode()
是所有 Map
条目的 hashCode()
的函数。条目的 hashCode()
是键和值的 hashCode()
的函数(在您的情况下都是 hm
)。因此,为了计算 hm.hashCode()
,您必须计算 hm.hashCode()
。这导致无限递归。
调用 hm.get(hm);
需要计算 hm.hashCode()
,导致无限递归和 WhosebugError
。
能否请您解释一下以下场景?
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 WhosebugError
尝试将 HashMap
作为键放在自身内部是个坏主意。
在 hm.put(hm,hm)
之后,您的 HashMap
包含一个 hashCode()
为 hm.hashCode()
的键。 hm.hashCode()
是所有 Map
条目的 hashCode()
的函数。条目的 hashCode()
是键和值的 hashCode()
的函数(在您的情况下都是 hm
)。因此,为了计算 hm.hashCode()
,您必须计算 hm.hashCode()
。这导致无限递归。
调用 hm.get(hm);
需要计算 hm.hashCode()
,导致无限递归和 WhosebugError
。