java - java中不同对象的长hashCode返回相同的数字

标签 java hashcode

假设我有这种情况

    Long id = -1L;
    System.out.println( id.hashCode() );

    id = 0L;
    System.out.println( id.hashCode() );

你猜怎么着?两个输出给出相同的数字(0)!我的问题是:

  1. 为什么会发生这种情况?
  2. 我怎样才能忽略这个并计算 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/

相关文章:

java - 在java中读取unicode字符

java - 如何从 String.hashCode() 值获取字符串?

java - 哈希码是在调用 hashcode() 方法时生成的

java - Java 线程二叉搜索树

java - 为不带参数的 boolean 方法编写 Junit 测试

java - 我无法使用通用类打印对象的值

Java 到 Cpp 代码转换 : compareTo

c# - 我应该使用我的字符串字段的串联作为哈希码吗?

php - 方法适用于 C++,但如何在 PHP 中重现相同的方法?

java - 如果哈希码被重写以使其仅返回一个常数,Hashmap 键将如何表现?