gpt4 book ai didi

java - 关于整数比较的澄清?

转载 作者:行者123 更新时间:2023-12-02 15:23:20 25 4
gpt4 key购买 nike

class Demo{
public static void main(String[] args) {
Integer i = Integer.valueOf(127);
Integer j = Integer.valueOf(127);

System.out.println(i==j);

Integer k = Integer.valueOf(128);
Integer l = Integer.valueOf(128);

System.out.println(k==l);
}
}

第一个打印语句打印 true,而第二个打印语句打印 false。为什么?请详细说明。

最佳答案

这是因为整数缓存。

来自java language specification 5.1.7

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.

理想情况下,对给定的原始值 p 进行装箱将始终产生相同的引用

Integer i = Integer.valueOf(127);  
Integer j = Integer.valueOf(127);

ij都指向同一个对象。因为值小于127。

Integer k = Integer.valueOf(128);  
Integer l = Integer.valueOf(128);

kl 都指向不同的对象。因为值大于 127。
当您使用 == 运算符检查对象引用时,您会得到不同的结果。

<小时/>

更新

您可以使用equals()方法获得相同的结果

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
  1. == 运算符检查实际的对象引用。
  2. equals()检查对象的值(内容)。
<小时/>

回复评论

你有,

Integer i = Integer.valueOf(127); 

这里创建了新对象并将引用分配给i

Integer j = Integer.valueOf(127); //will not create new object as it already exists 

由于整数缓存(-128到127之间的数字),之前创建的对象引用被分配给j,然后ij指向到相同的对象。

现在考虑一下,

Integer p = Integer.valueOf(127); //create new object 
Integer q = Integer.valueOf(126); //this also creates new object as it does not exists

显然,使用 == 运算符和 equals() 方法进行检查都会得到 false 的结果。因为两者是不同的引用并且具有不同的值。

关于java - 关于整数比较的澄清?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19464554/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com