public class AutoBoxDemo3 {
    public static void main(String[] args) {
        Integer i1 = 200;
        Integer i2 = 200;
 
        if (i1 == i2) 
            System.out.println("i1 == i2");
        else 
            System.out.println("i1 != i2"); Integer i11 = 100;
        Integer i21 = 100;
 
        if (i11 == i21) 
            System.out.println("i11 == i21");
        else 
            System.out.println("i11 != i21");
    }
}
运行结转果是:i1!=i2
            i11=i21为什么?

解决方案 »

  1.   

    java在编译的时候 Integer a = 100; 被翻译成-> Integer a = Integer.valueOf(100);
    比较的时候仍然是对象的比较,在jdk源码中
    public static Integer valueOf(int i) { 
    final int offset = 128; 
    if (i >= -128 && i <= 127) { // must cache 
    return IntegerCache.cache[i + offset]; 

    return new Integer(i); 
    } 而
    private static class IntegerCache { 
    private IntegerCache(){} 
    static final Integer cache[] = new Integer[-(-128) + 127 + 1]; 
    static { 
    for(int i = 0; i < cache.length; i++) 
    cache = new Integer(i - 128); 



    这边是java为了提高效率,初始化了-128--127之间的整数对象
    所以在赋值在这个范围内都是同一个对象。
    再加一句
    Integer a = 100;
    a++;
    //这边a++是新创建了一个对象,不是以前的对象。
        public static void main(String []args) {
            Integer a = 100;
            Integer b = a;
            a++;
            System.out.println(a==b);
        }
    打印就是false
    对于127--128没有多大关系,但是在这范围之外就影响性能了吧,就像StringBuffer VS String一样了
    哈哈,找到段比较好的解释,就是这样的吧
      

  2.   

    自动打包规范要求boolean byte char<=127 介于-128~127之间的short和int被包装到固定的对象中
      

  3.   

    支持4楼`````
    包装后最好用equals  做比较`
      

  4.   

    2楼解释的很好,但是怀疑你贴错一点大妈for(int i = 0; i  < cache.length; i++)  
    cache = new Integer(i - 128);  
    }  
    应该是for(int i = 0; i  < cache.length; i++)  
    cache[i] = new Integer(i - 128);  
    }  
    }  ???
     
      

  5.   

    楼上的看的很仔细
    cache是一个数组,2楼的兄弟居然没注意.....
      

  6.   

    为啥要用Integer呢?真不大明白。有高手解释下什么情况用Integer么?
      

  7.   

    Integer是个类,它不同于 int  上面的i1,i2是两个对象的两个引用,当然会显示i1!=i2 。