之前一直没有特别关注这个问题,以为只有面试时才会用到,直到最近遇到一个大坑,遂总结相关知识,今后面试也好用到
什么是自动装箱拆箱
// 装箱:自动根据数值创建对应的Integer对象
Integer i = 10;
// 拆箱:将包装器类型转换为基本数据类型
Integer n = 10;
int m = i;
自动装箱拆箱的实现
根据反编译结果可知:
- 装箱自动调用
Integer
的valueOf(int)
方法 - 拆箱自动调用
Integer
的intValue
方法
其他的包装器类型如Double、Character也类似
因此自动装箱拆箱可以用一句话总结:装箱过程是通过调用包装器的valueOf
方法实现的,而拆箱过程是通过调用包装器的 xxxValue
方法实现的
缓冲池
先来看一下Integer类中的 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);
}
new Integer(123)
与 Integer.valueOf(123)
的区别在于
new Integer(123)
每次都会新建一个对象Integer.valueOf(123)
则会使用cache中的对象,多次调用会取得同一个对象的引用
在Java8中,IntegerCache的大小默认为-128 ~ 127
private static class IntegerCache {
static final int low = -128;
static final int high;
static final Integer cache[];
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) {
try {
int i = parseInt(integerCacheHighPropValue);
i = Math.max(i, 127);
// Maximum array size is Integer.MAX_VALUE
h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
} catch( NumberFormatException nfe) {
// If the property cannot be parsed into an int, ignore it.
}
}
high = h;
cache = new Integer[(high - low) + 1];
int j = low;
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);
// range [-128, 127] must be interned (JLS7 5.1.7)
assert IntegerCache.high >= 127;
}
private IntegerCache() {}
}
举例
int a = 100;
Integer b = 100;
System.out.println(a == b); // true
Integer c = 100;
Integer d = 100;
System.out.println(c == d); // true
Integer e = new Integer(100);
Integer f = new Integer(100);
System.out.println(e == f); // false 两对象比较没有进行装箱拆箱
Integer g = 200;
Integer h = 200;
System.out.println(g == h); // false 超出Cache
主要参考资料:
https://www.cnblogs.com/dolphin0520/p/3780005.html