在java.util.HashMap.TreeNode#putTreeVal()中有一些代码,如下所示:
if ((ph = p.hash) > h)
dir = -1;
else if (ph < h)
dir = 1;
else if ((pk = p.key) == k || (k != null && k.equals(pk)))
return p;
else if ((kc == null &&
(kc = comparableClassFor(k)) == null) ||
(dir = compareComparables(kc, k, pk)) == 0) {
if (!searched) {
TreeNode q, ch;
searched = true;
if (((ch = p.left) != null &&
(q = ch.find(h, k, kc)) != null) ||
((ch = p.right) != null &&
(q = ch.find(h, k, kc)) != null))
return q;
}
dir = tieBreakOrder(k, pk);
}
有两种情况:h小于ph,h大于ph.
通常,代码(pk = p.key)== k || (k!= null&& k.equals(pk))表示h等于ph,但我不知道为什么之后还存在其他内容.
当两个对象的hashCode彼此相等,但==和euqlas()会为假时,情况如何?
当Object的类重写equals()方法会导致这种情况吗?但是我曾经听说,覆盖equals()也必须覆盖hashCode(),所以这个问题不会发生.
我希望有人能告诉我哪种情况会导致其他情况.
解决方法:
What is the situation when two objects’s hashCode is equals to each
other, but == and equals() will get false?
根据Java文档:
>如果对象相等(即x.equals(y)== true),则这些对象的hashCode也应相等(即x.hashCode()== y.hashCode())
>如果两个对象具有相同的hashCode(即x.hashCode()== y.hashCode()),则这些对象并不一定要相等(即x.equals(y)== true / false)
标签:hashmap,java
来源: https://codeday.me/bug/20191108/2006932.html