关于整数比较的澄清?

Pra*_*hra 2 java autoboxing integer value-of

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);  
  }  
}
Run Code Online (Sandbox Code Playgroud)

第一个print语句打印为true,而第二个打印语句打印为false.为什么?请详细解释.

Ani*_*rni 5

这是因为Integer缓存.

来自java语言规范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.  
Run Code Online (Sandbox Code Playgroud)

理想情况下,装箱给定的原始值p将始终产生相同的参考.

Integer i = Integer.valueOf(127);  
Integer j = Integer.valueOf(127);   
Run Code Online (Sandbox Code Playgroud)

双方ij指向同一个对象.因为该值小于127.

Integer k = Integer.valueOf(128);  
Integer l = Integer.valueOf(128);   
Run Code Online (Sandbox Code Playgroud)

这两个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 
Run Code Online (Sandbox Code Playgroud)

输出是

true
true  
Run Code Online (Sandbox Code Playgroud)
  1. == 运算符检查实际的对象引用.
  2. equals() 检查对象的值(内容).

回答评论

你有,

Integer i = Integer.valueOf(127); 
Run Code Online (Sandbox Code Playgroud)

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

Integer j = Integer.valueOf(127); //will not create new object as it already exists 
Run Code Online (Sandbox Code Playgroud)

由于整数缓存(-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  
Run Code Online (Sandbox Code Playgroud)

显然==,equals()将导致使用运算符和方法的两个检查false.因为两者都是不同的引用并且具有不同的值.