【问题标题】:Clarification regarding Integer comparison? [duplicate]关于整数比较的澄清? [复制]
【发布时间】:2013-10-19 09:35:24
【问题描述】:
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);  
  }  
}

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

【问题讨论】:

标签: java integer autoboxing value-of


【解决方案1】:

这是因为整数缓存。

来自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。因为两者都是不同的引用,并且具有不同的值。

【讨论】:

  • 能否详细说明“i和j指向同一个引用”和“k和l指向不同的引用”
  • @PrasoonMishra:请查看更新后的帖子。我希望你的疑惑能解开。阅读更新后的帖子有任何疑问,请告诉我。谢谢。
【解决方案2】:
   i==j

由于整数缓存,true 的值介于 -128127 之间。

来自language spec

如果被装箱的值 p 是真、假、一个字节或 \u0000 到 \u007f 范围内的一个字符,或者一个介于 -128 和 127(包括)之间的 int 或短数字,则令 r1 和 r2 为p 的任意两次装箱转换的结果。 r1 == r2 总是如此。

   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

所以ij 指向同一个引用,因为值为 127。

kl 指向差异引用,因为它们的值 >127

文档中提到了这种行为的原因:

该行为将是理想的行为,而不会造成过度的性能损失,尤其是在小型设备上。更少的内存限制实现可能

【讨论】:

    【解决方案3】:

    valueOf 返回一个整数对象。 Integer 是 int 的包装类。对于您的情况,

    Integer == Integer 比较实际的对象引用,其中 int == int 将比较值。

    如前所述,值 -128 到 127 被缓存,因此为这些值返回相同的对象。

    如果超出该范围,将创建单独的对象,因此引用将不同。

    如果您希望两种情况的结果相同,请通过以下方式修复它:

    • 将类型设为 int
    • 将类型转换为 int 或
    • 使用 .equals()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-22
      • 2011-06-15
      • 2010-12-24
      • 1970-01-01
      相关资源
      最近更新 更多