java - 关于 Object.hashcode() 和冲突

标签 java hashcode hash-collision

我正在阅读 JavaDoc对于 Object.hashCode 方法,它表示

As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer [...])

但无论它的实现是什么,hashCode 方法总是返回一个(让我们假设为正)整数,所以给定 Integer.MAX+1 不同的对象,其中两个将具有相同的哈希码。

为什么 JavaDoc 在这里“拒绝”冲突?鉴于使用了内部地址并且“来吧,你永远不会在内存中立即拥有 Integer.MAX+1 对象,这是一个实际的结论吗,所以我们可以说它实际上是总是独一无二的”?

编辑

bug entry (谢谢 Sleiman Jneidi )给出了我的意思的确切概念(这似乎是一个超过 10 年的讨论):

appears that many, perhaps majority, of programmers take this to mean that the default implementation, and hence System.identityHashCode, will produce unique hashcodes.

The qualification "As much as is reasonably practical," is, in practice, insufficient to make clear that hashcodes are not, in practice, distinct.

最佳答案

文档确实具有误导性,并且有一个 bug很久以前打开说文档具有误导性,尤其是实现依赖于JVM,并且在实践中,尤其是在堆大小很大的情况下,将对象标识映射到 32 位整数时很可能会发生冲突

关于java - 关于 Object.hashcode() 和冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34333792/

相关文章:

java - 如何从Spring Security获取密码?

sql - 在postgresql中查找一行的哈希值

java - 确定骑士守卫的平方数

python - CSP 不接受内联脚本哈希或随机数

c - 在 C 中寻找数组(与链表)哈希表实现

java - 如何以编程方式设置 jTree 子级的选择

java - Spring Boot MongoDb 集合

hash - 两个不同的字符串可以生成相同的MD5哈希码吗?

java - 为什么我的哈希表不允许键冲突?

java - 用 Java 设计数据访问类