Java 关于整数比较的澄清?
第一个print语句输出true,而第二个语句输出false。为什么?Java 关于整数比较的澄清?,java,integer,autoboxing,value-of,Java,Integer,Autoboxing,Value Of,第一个print语句输出true,而第二个语句输出false。为什么? 请详细解释。这是因为整数缓存 从 理想情况下,装箱给定的原语值p将始终产生相同的引用 If the value p being boxed is true, false, a byte, or a char in the range \u0000 to \u007f, or an int or short number between -128 and 127 (inclusive), then let r1 and r
请详细解释。这是因为整数缓存 从 理想情况下,装箱给定的原语值p将始终产生相同的引用
If the value p being boxed is true, false, a byte, or a char in the range
\u0000 to \u007f, or an int or short number between -128 and 127 (inclusive),
then let r1 and r2 be the results of any two boxing conversions of p.
It is always the case that r1 == r2.
i
和j
都指向同一个对象。因为该值小于127
Integer i = Integer.valueOf(127);
Integer j = Integer.valueOf(127);
k
和l
都指向不同的对象。因为该值大于127。当您使用
=
操作符检查对象引用时,会得到不同的结果
更新 您可以使用
equals()
方法获得相同的结果
Integer k = Integer.valueOf(128);
Integer l = Integer.valueOf(128);
输出为
System.out.println(i.equals(j));//equals() compares the values of objects not references
System.out.println(k.equals(l));//equals() compares the values of objects not references
=
运算符检查实际对象引用李>
回复评论 你有
true
true
在这里创建新对象并将引用分配给i
Integer i = Integer.valueOf(127);
由于整数缓存(数字介于-128到127之间),先前创建的对象引用被分配给j
,然后i
和j
指向相同的对象
现在考虑,
Integer j = Integer.valueOf(127); //will not create new object as it already exists
显然,使用==
运算符和equals()
方法进行的两种检查都将导致false
。因为两者都是不同的参考,具有不同的值
Integer p = Integer.valueOf(127); //create new object
Integer q = Integer.valueOf(126); //this also creates new object as it does not exists
由于整数缓存,对于介于-128
和127
之间的值,为true
从
如果要装箱的值p为true、false、一个字节或\u0000到\u007f范围内的字符,或一个介于-128和127(包括-128和127)之间的整数或短数字,则让r1和r2为p的任意两个装箱转换的结果。r1==r2总是这样
因此,由于值127,i
和j
指向相同的引用
其中ask
和l
指向不同的引用,因为它们的值>127
文档中提到了这种行为的原因:
该行为将是期望的,不会对性能造成不适当的惩罚,尤其是在小型设备上。内存限制较少的实现可能会返回整数对象。Integer是int的包装类。对于您的情况 Integer==Integer比较实际对象引用,其中int==int将比较值 如前所述,缓存值-128到127,因此为这些值返回相同的对象 如果超出该范围,将创建单独的对象,因此引用将不同 如果您希望两种情况的结果相同,可以通过以下方式进行修复:
- 使类型为int
- 将类型强制转换为int或
- 使用.equals()
Integer p = Integer.valueOf(127); //create new object
Integer q = Integer.valueOf(126); //this also creates new object as it does not exists
i==j
Integer i = Integer.valueOf(127); // new object
Integer j = Integer.valueOf(127); //cached object reference
Integer k = Integer.valueOf(128); // new object
Integer l = Integer.valueOf(128); // new object