java - 为什么 new Integer(i).hashCode() 会返回 i?

标签 java hashcode

我想知道为什么 new Integer(i).hashCode()new Long(i).hashCode() 返回 i但是当 hashCode() 被其他对象调用时,比如 new Double(345).hashCode(),它返回一个随机数。为什么?

最佳答案

因为Integerint值完美满足并完全符合Object.hashCode()的总契约:

The general contract of hashCode is:

  • Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.

  • If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.

  • It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables.

简而言之:

如果 equals() 返回 true,则 2 个对象的哈希码必须相同,并且应该 (但不是必需的)如果 equals() 返回 false 则不同。同样通过 Object.hashCode() 的声明,它必须是一个 int。理想情况下,哈希码应取决于所有经过哈希处理的数据。

的哈希码

Long 必须将 8 个字节映射到 4 个字节(int 的大小)。 Long.hashCode() 的当前实现只会在它适合 int 时返回 i,否则它将与上层进行异或运算32 位(4 字节):

return (int)(value ^ (value >>> 32));

Double的哈希码

显然 Doubledouble 值不符合此要求。 Double 也必须将 8 个字节映射到 4 个字节。

Double.hashCode() 将返回一个看似随机的值,因为 float (floatdouble)没有“很好地”存储(例如 2 的补码,如 intlong)在为它们保留但使用 IEEE 754 binary floating point standard 的字节中因此将这 8 个字节映射到 4 个字节(这正是实现所做的)将不是一个有意义的数字,因为 int 使用 2 的补码表示。

long bits = doubleToLongBits(value);
return (int)(bits ^ (bits >>> 32));

关于java - 为什么 new Integer(i).hashCode() 会返回 i?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26781550/

相关文章:

java - 从套接字读取时获取空字符串

java - 为什么ArrayList在插入数据后会改变它的hashcode?

java - 一种节省空间的数据结构,用于存储和查找大量(均匀分布的)整数

java - 压缩方法在哈希表中会做什么?

java - 使用 hashCode() 测试字符串相等性

java - Guava.Objects.hashCode 与 Java.Objects.hashCode

java - 为什么 else 语句没有初始化?

java - 在 iText 中合并两个模板

java - 启用/禁用 NTAG213 计数器

java - 在java中检查电子邮件抄送字段是否有错误电子邮件地址的最佳方法是什么