首页 > 解决方案 > 为什么两个具有相同值的原始双精度数具有两个不同的identityHashCode?

问题描述

我了解到所有具有相同值的原语都相同identityHashCode,所以我想要identityHashCode一些原语。所以当我尝试使用 2 个具有相同值的双精度时,它给出的结果不同identityHashCode,我做了以下操作:

int xInt=5;
int yInt=5;

System.out.println(System.identityHashCode(xInt));//output:1867083167
System.out.println(System.identityHashCode(yInt));//output:1867083167

double double1=5;
double double2=5;


System.out.println(System.identityHashCode(double1));//output:1915910607

System.out.println(System.identityHashCode(double2));//output:1284720968

两个具有相同值的整数具有相同的值,identityHashCode但是具有相同值的两个双精度值却不同identityHashCode,这是为什么?

标签: javadouble

解决方案


您的代码正在装箱原始值。(原始值本身没有标识哈希码,因为这只是一个与对象相关的概念。)您的代码等效于:

int xInt=5;
int yInt=5;

Integer xInteger = xInt;
Integer yInteger = yInt;

System.out.println(System.identityHashCode(xInteger));
System.out.println(System.identityHashCode(yInteger));

double double1=5;
double double2=5;

Double boxedDouble1 = double1;
Double boxedDouble2 = double2;

System.out.println(System.identityHashCode(boxedDouble1));
System.out.println(System.identityHashCode(boxedDouble2));

现在,如果您比较参考资料本身,您会发现这xInteger == yInteger是对的,但boxedDouble1 == boxedDouble2也是错的……identityHashCode准确地表示这种关系也是如此。

您的盒装整数引用引用同一对象的原因是特定范围内的盒装整数类型被缓存

如果被装箱的值 p 是对 boolean、char、short、int 或 long 类型的常量表达式 (§15.28) 求值的结果,并且结果为 true、false,则为 '\u0000' 到 ' 范围内的字符\u007f' 或 -128 到 127 范围内的整数(含),则令 a 和 b 为 p 的任意两次装箱转换的结果。a == b 总是如此。

实际上,该范围实际上可以更大,并且实现也可以缓存盒装双打,但我还没有看到这种情况发生。


推荐阅读