关于Object.hashcode()和冲突 [英] About Object.hashcode() and collisions
问题描述
我正在阅读 JavaDoc 表示Object.hashCode
方法
在合理可行的范围内,由Object类定义的hashCode方法确实为不同的对象返回不同的整数. (通常通过将对象的内部地址转换为整数[...]来实现)
但是无论其实现是什么,hashCode
方法始终返回一个(假设为正数)整数,因此,给定Integer.MAX+1
不同的对象,它们中的两个将具有相同的哈希码.
为什么JavaDoc在这里拒绝"冲突?鉴于使用了内部地址并且"来了,您永远不会在内存中立即拥有Integer.MAX+1
对象,所以我们可以说它实际上总是唯一的"是一个实际的结论吗?/p>
编辑
此错误条目(感谢您Sleiman Jneidi )给出了我的意思的精确概念(这似乎已有10多年的历史了):
似乎有很多(也许是大多数)程序员将此表示为默认实现,因此System.identityHashCode将产生唯一的哈希码.
实际上,在合理范围内尽可能多"的限定条件不足以使哈希码在实践中并不明显.
该文档确实具有误导性,并且存在JavaDoc for Object.hashCode
method, it says that
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 [...])
But whatever its implementation is, hashCode
method always returns a (let's assume positive) integer, so given Integer.MAX+1
different objects, two of them are going to have the same hashcode.
Why is the JavaDoc here "denying" collisions? Is it a practical conclusion given that internal address is used and "come on, you're never going to have Integer.MAX+1
objects in memory at once, so we can say it's practically always unique"?
EDIT
This bug entry (thank you Sleiman Jneidi) gives an exact idea of what I mean (it seems to be a more that 10 years old discussion):
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.
The docs are misleading indeed, and there is a bug opened ages ago that says that the docs are misleading especially that the implementation is JVM
dependent, and in-practice especially with massive heap sizes it is so likely to get collisions when mapping object identities to 32-bit integers
这篇关于关于Object.hashcode()和冲突的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!