假设我有这种情况
Long id = -1L;
System.out.println( id.hashCode() );
id = 0L;
System.out.println( id.hashCode() );
你猜怎么着?两个输出给出相同的数字(0)!我的问题是:
- 为什么会发生这种情况?
- 我怎样才能忽略这个并计算 0 和 -1 的正确哈希值?
提前感谢您的回复:)
最佳答案
Why is this happening?
因为Long.hashCode
的实现是as follows :
<小时/>The result is the exclusive OR of the two halves of the primitive long value held by this Long object. That is, the hashcode is the value of the expression:
(int)(this.longValue()^(this.longValue()>>>32))
How can I omit this and calculate proper hash for 0 and -1 ?
这些是正确的哈希值。不保证哈希值是唯一的;事实上,如果可能的输入值超过 232 个,它们就保证不是唯一的。
如果您想要不同的行为,则需要编写一个行为不同的 MyInteger
类(尽管我怀疑没有真正好的理由这样做)。
关于java - java中不同对象的长hashCode返回相同的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26713397/