分析&回答
包装类:Byte,Short,Integer,Long,Character
他们使用static代码块进行初始化缓存,其中Integer的最大值可以通过high设置;Boolean使用static final实例化的对象;Float和Double直接new的对象没有使用缓存。
Integer举例如下:
Integer a = 127;
Integer b = 127;
log.info("S:{}",a == b );
Integer c = 128;
Integer d = 128;
log.info("X:{}",c == d );
输出
S:true
X:false
默认范围:在-128到127之间使用自动装箱时,会使用缓存。范围的最大值可以通过java.lang.Integer.IntegerCache.high设置,通过for循环将范围内的数据实例化为Integer对象放到cache数组里,如下面代码:
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() {}
}
反思&扩展
使用自动装箱将基本类型转为封装类对象这个过程其实底层实现是调用封装类的valueOf方法:
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
喵呜面试助手: 一站式解决面试问题,你可以搜索微信小程序 [喵呜面试助手] 或关注 [喵呜刷题] -> 面试助手 免费刷题。如有好的面试知识或技巧期待您的共享!