我了解到所有具有相同值的图元都具有相同的值,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
Run Code Online (Sandbox Code Playgroud)
具有相同值的两个整数具有相同的值,identityHashCode但具有相同值的两个双精度值却具有不同的identityHashCode原因?
您的代码将原始值装箱。(原始值本身没有标识哈希码,因为这只是与对象相关的概念。)您的代码等效于此:
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));
Run Code Online (Sandbox Code Playgroud)
现在,如果您比较引用本身,您会发现这xInteger == yInteger是正确的,但是boxedDouble1 == boxedDouble2是错误的……因此identityHashCode可以准确地表示这种关系。
装箱的整数引用引用同一对象的原因是,将缓存特定范围内的装箱的整数类型:
如果要装箱的值p是对布尔类型,char,short,int或long类型的常量表达式(第15.28节)求值的结果,并且结果为true,false,则是'\ u0000'到' \ u007f'(含)或-128至127(含)范围内的整数,则令a和b为p的任何两次装箱转换的结果。总是a == b。
实际上,范围可以更大,并且实现也可以缓存盒装双打,但我还没有看到这种情况。