java自动装箱拆箱原理
看了很多博主都没写原理,只是浅显地说了自动装箱拆箱的含义,我就把这个必须知道的知识写一下吧
1.自动装箱
以int -> Integer为例,Integer integer = 1;
编译器编译过程中自动调用这个方法:
Integer integer = Integer.valueOf(1);
将int转换成Integer对象
注意
默认情况下,
装箱时int在[-128,127]
范围时从IntegerCache
类中的chche[]
数组中返回一个现有的Integer对象
超过范围则返回一个新Integer对象。
//Integer的valueOf方法
public static Integer valueOf(int i) {
assert IntegerCache.high >= 127;
if (i >= IntegerCache.low && i <= IntegerCache.high)
//这里数组下标从0开始,所以索引要加128
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
(拓展)再注意一点:
缓存Integer对象的范围也是可以配置的,这是IntegerCache的静态代码块:
static {
// high value may be configured by property
int h = 127;
String integerCacheHighPropValue =
sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
if (integerCacheHighPropValue != null) {
int i = parseInt(integerCacheHighPropValue);
i = Math.max(i, 127);
// Maximum array size is Integer.MAX_VALUE
h = Math.min(i, Integer.MAX_VALUE - (-low));
}
high = h;
cache = new Integer[(high - low) + 1];
int j = low;
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);
}
2.自动拆箱
和装箱类似,自动调用Integer对象的intValue()
方法;
如:int i = integer;编译时会自动调用:
int i = integer.intValue();
3.注意事项
(1)相同int经过自动装箱的Integer对象有可能是同一对象也可能不是,所以对Integer比较时应用equals()
方法.
(2)int的默认值为0,而Integer引用默认为null.