在HashMap
的实现细节中,我可以看到:
When using comparators on insertion, to keep a
* total ordering (or as close as is required here) across
* rebalancings, we compare classes and identityHashCodes as
* tie-breakers.
如果我有常量 hashCode
和很好的 equals
而我的类没有实现 Comparable
它究竟会如何打破关系以及如何会建树吗?
我的意思是 - 桶将转换为树并使用 System.identityHashCode
打破平局。
然后我将尝试使用不同的实例调用 containsKey
方法(它将具有相同的 hashCode
和 a.equals(b) == true
) 它会有不同的 identityHashCode
那么树是否有可能被错误的节点(左而不是右)遍历并且找不到键?
我是不是遗漏了什么或者这是正常行为?
最佳答案
在引用部分之前解释了身份哈希代码基打破平局的动机:
* When bin lists are treeified, split, or untreeified, we keep * them in the same relative access/traversal order (i.e., field * Node.next) to better preserve locality, and to slightly * simplify handling of splits and traversals that invoke * iterator.remove. When using comparators on insertion, to keep a * total ordering (or as close as is required here) across * rebalancings, we compare classes and identityHashCodes as * tie-breakers.
因此,按身份哈希码排序提供了稳定的排序,有助于实现拆分和 Iterator.remove()
操作(必须支持持续遍历)。
如 this answer 中所述,它不用于查找操作,正如您在问题中已经说过的,两个相同的对象可能具有不同的身份代码。因此,对于具有相同哈希码且未实现 Comparable
的不相等对象,无法遍历所有对象并通过 equals
进行探测。
关于java - HashMap 桶中的 IdentityHashCode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53658426/