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为什么?
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为什么?
比较的时候仍然是对象的比较,在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一样了
哈哈,找到段比较好的解释,就是这样的吧
包装后最好用equals 做比较`
cache = new Integer(i - 128);
}
} 应该是for(int i = 0; i < cache.length; i++)
cache[i] = new Integer(i - 128);
}
} ???
cache是一个数组,2楼的兄弟居然没注意.....