public class TestWrappedClass {
public static void main(String[] args) {
Integer c = 1228;//自动装箱 等于 Integer.valueOf(1228); 编译器会自动帮你添加
Integer d = 1228;
System.out.println(c == d);//false c和d是两个不同的对象 在堆里面不一样
System.out.println(c.equals(d));//true值相同
}
}
不过当包装的值为-128时会出现这个情况
public class TestWrappedClass {
public static void main(String[] args) {
Integer a = -128;
Integer b = -128;
System.out.println(a == b);//true
System.out.println(a.equals(b));//true
}
}
按照之前测试的结果 a == b 应该为false,但是你看源码可以发现,在执行Integer.valueof()时会先查询包装的数字的对象是否在缓存里,low为-128 high = 127,如果不在缓存里既超过(-128,127)的范围则会新建对象.所以因为-128在范围里,则c和d的对象在堆里是同一个,所以c==d为true。
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);//新建对象
}