从演示代码开始分析:
public class Autoboxing {
public static void main(String[] args){
Integer a = 1;
Integer b = 2;
Integer c = 3;
Integer d = 3;
Integer e = 321;
Integer f = 321;
Long g = 3L;
System.out.println(c == d);//true -128 ~ 127之间的值从IntegerCache 的cache数组中取值,拿到的是同一个对象 cache[129]
System.out.println(e == f);//false 大于127、小于-128的值 通过new Integer()来创建对象
System.out.println(c == (a + b));//true == 包装类在遇到算术运算符会自动拆箱
System.out.println(c.equals(a + b));// true equals方法会同时比较类型和值是否相同
System.out.println(g == (a + b));//true == 包装类在遇到算术运算符会自动拆箱
System.out.println(g.equals(a + b));//false 包装类的equals方法不处理数据转型的关系
}
}
分析:
在程序执行 Integer a =1这句代码时,会进行自动装箱,调用 Integer.valueOf()方法,查看Integer.valueOf方法源代码:
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
其中,IntegerCache.low = -128, IntegerCache.high = 127;因此,对于Integer类型的数字,如果数字大于等于-128且小于等于127,自动装箱返回的是IntegerCache.cache[]数组对象;如果数字大于127且小于等于2^32-1 或者 大于等于-2^32小于-128,自动装箱返回一个Integer对象。