装箱:基本数据类型 转换为 包装类型。
拆箱:包装类型 转换为 基本数据类型。
为什么会有“自动”装、拆箱这个概念?
“自动"其实是底层调用了Integer类中的方法。只不过没有在表面上体现出来,但是在底层会有体现。
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
在自动装箱中,底层其实调用了Integer类中的valueOf()方法。这段代码的意思是:如果你传的这个参数是在[-128~127]这个条件中,那么会直接从缓存cache(数组)中所存的这256个数字中返回。如果不再[-128~127]这个条件中,那么,在方法的最后调用了Integer的构造方法 public Integerr(int value),把参数i传到构造方法里,返回一个Integer类型的200,其实就是
Integer in=new Integer(200)。参数i就是我们自己定义的基本数据类型。这也就是为什么当你包装两个大于127的基本类型数字,让这两个数字进行==判断时,运行结果会是false,就是因为new了两次,new两次的内存地址是不一样的。
这段源码中提到了到IntegerCache.low 这里的IntegerCache是Integer中的一个内部类,表示为Integer缓存。low是这个内部类中的一个静态的常量,是-128。IntegerCache.high中的high表示的也是一个静态常量,是在静态代码块中给这个high初始化,赋值127。
以下的代码是这个内部类的出处。
private static class IntegerCache {
static final int low = -128;
static final int high;
static final Integer[] cache;
static Integer[] archivedCache;
static {
// high value may be configured by property
int h = 127;
String integerCacheHighPropValue =
VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
if (integerCacheHighPropValue != null) {
try {
h = Math.max(parseInt(integerCacheHighPropValue), 127);
// Maximum array size is Integer.MAX_VALUE
h = Math.min(h, Integer.MAX_VALUE - (-low) -1);
} catch( NumberFormatException nfe) {
// If the property cannot be parsed into an int, ignore it.
}
}
high = h;
// Load IntegerCache.archivedCache from archive, if possible
VM.initializeFromArchive(IntegerCache.class);
int size = (high - low) + 1;
// Use the archived cache if it exists and is large enough
if (archivedCache == null || size > archivedCache.length) {
Integer[] c = new Integer[size];
int j = low;
for(int i = 0; i < c.length; i++) {
c[i] = new Integer(j++);
}
archivedCache = c;
}
cache = archivedCache;
// range [-128, 127] must be interned (JLS7 5.1.7)
assert IntegerCache.high >= 127;
}
这段代码的意思是:low的默认值是-128,high值初始化127,我们可以通过jvm的修改配置参数的方法对high手动进行调整(因为java默认high是127),最后high会被修改成我们设置的值,由于我们没有手动调整,所以这里默认high是127。然后会把[-128~127]这256个数字添加到缓存catch(数组)中。所以catch[]的取值范围是[-128~127]。