自动拆箱与装箱:其实就是调用了valueOf 和 parseXXX方法
易错点:
Integer a1 = 127;
Integer a2 = 127;
int a3 = 127;
Integer b1 = 128;
Integer b2 = 128;
int b3 = 128;
System.out.println(a1==a2);
System.out.println(a1==a3);
System.out.println(b1==b2);
System.out.println(b1==b3);
true
true
false
true
解析:
a1,a2左边是Integer而右边是int,所以会自动装箱,也就是调用valueOf( int value)方法。我们查看方法源码如下:
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
可以看到如果 i 在【IntegerCache.low,IntegerCache.high】范围时,会直接返回一个已经存在的值,如果不在这个范围的话会new一个值。我们再继续查看这个范围到底是多少。
static final int low = -128;
static final int high;
int h = 127;
high = h;
static final Integer cache[];