自动装箱拆箱操作员(!=)和(==)区别

时间:2013-12-26 12:12:23

标签: java autoboxing unboxing

public class T1 {    

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Integer i1 = 1000;
        Integer i2 = 1000;
        if(i1 != i2) System.out.println("different objects");
        if(i1.equals(i2)) System.out.println("meaningfully equal");    

    }

}

O / P就是:

  

不同的对象
  有意义的等于

在哪里

public class T2 {    

    public static void main(String[] args) {            

        Integer i3 = 10;
        Integer i4 = 10;
        if(i3!=i4)System.out.println("Crap dude!!");
        if(i3 == i4) System.out.println("same object");

        if(i3.equals(i4)) System.out.println("meaningfully equal");    
    }

}

产生以下O / P:

  

同一对象
  有意义的等于

我不明白为什么在课堂上T2 if(i3!=i4)没有被触发我在推荐SCJP 1.6但是无法理解。
请帮帮我。

5 个答案:

答案 0 :(得分:10)

这是因为10在[-128,127]范围之间。对于此范围==工作正常,因为JVM缓存值,并且将在相同的对象上进行比较。

每次使用该范围内的值创建Integer(对象)时,将返回相同的对象,而不是创建 new 对象。

有关详细信息,请参阅JLS

答案 1 :(得分:4)

java中有来自-128 to 127的数字的整数池。 JLS

  

如果框中的值p为true,false,则为字节或字符   范围\ u0000到\ u007f,或介于-128和127之间的int或短数字   (包括),然后让r1和r2成为任意两个拳击的结果   转换p。始终是r1 == r2。

的情况      

理想情况下,装箱给定的原始值p总会产生一个   相同的参考。在实践中,这可能是不可行的   现有的实施技术。上述规则是务实的   妥协。上面的最后一个条款要求某些共同的价值   总是被装入无法区分的物体。实施可能   懒惰或急切地缓存这些。对于其他值,这个配方   不允许对盒装价值的身份做出任何假设   程序员的一部分。这将允许(但不要求)共享   部分或全部参考文献。

     

这确保了在大多数情况下,行为将是   期望的,特别是没有施加过度的性能损失   在小型设备上。对于内存限制较少的实现可能   例如,缓存所有char和short值,以及int和long   值范围为-32K至+ 32K。

答案 2 :(得分:4)

小整数得到实体化,这意味着给定值只有Integer的一个实例。

大整数不会发生这种情况,因此两次测试之间的行为不同。

答案 3 :(得分:2)

整数在-128到127之间缓存。因此范围之间的Integer(包含边界值)将返回相同的引用。

Integer i3 = 127;
Integer i4 = 127;
Integer i5 = 128;

 if(i3!=i4)System.out.println("Crap dude!!");   // same reference
 if(i3 == i4) System.out.println("same object"); 
 if(i3 != i5) System.out.println("different object");   

输出..

same object
different object

As'=='比较引用,'equals'比较内容。更多细节你可以去 Immutable Objects / Wrapper Class Caching

答案 4 :(得分:2)

无论如何你可以得到双重假:

Integer n1 = -1000;
Integer n2 = -1000;

Integer p1 = 1000;
Integer p2 = 1000;

System.out.println(n1 == n2);
System.out.println(p1 != p2);

可以选择设置此整数池的最大大小

  /**
   * Cache to support the object identity semantics of autoboxing for values between
   * -128 and 127 (inclusive) as required by JLS.
   *
   * The cache is initialized on first usage.  The size of the cache
   * may be controlled by the -XX:AutoBoxCacheMax=<size> option.
   * During VM initialization, java.lang.Integer.IntegerCache.high property
   * may be set and saved in the private system properties in the
   * sun.misc.VM class.
   */