基本数据类型包装成包装类叫做装箱,获取包装类对象中包装的基类型变量叫做拆箱。JDK1.3之后支持自动装箱自动拆箱。
接下来的这个示例就是自动装箱。为什么输出不一样的结果呢
Integer m = 1;
Integer n = 1;
System.out.println(m == n);//true
Integer x = 128;
Integer y = 128;
System.out.println(x == y);//flase
通过阅读Integer源码可以发现,
private static class IntegerCache {
static final int low = -128;
static {
// high value may be configured by property
int h = 127;
}
}
@HotSpotIntrinsicCandidate
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
Integer中有类IntegerCache,IntergerCache中定义了low和high,范围是-128–127,当数值在Cache缓存的范围内时第一次创建新的对象,再创建一样的值时直接拿过来用,超过Cache范围则每次都要创建新的对象。