概况
面试题中经常看到封装对象进行数据比较,判断是否相等的问题。一般可能想到因为是两个对象比较 == 判断的是对象引用的地址值,因此觉得不相同。实际上对象的内部存在缓存机制,例如:整数类型除了Integer之外其他的缓存区间都是 -128~127 ,下面通过查看源码来分析下。
Integer的缓存
常见的面试题
public static void main(String[] args) {
Integer i1 = 100;
Integer i2 = 100;
System.out.println("比较结果:" + (i1 == i2));
}
比较结果:true
这个就涉及到 自动装箱(valueOf())方法,这个可以通过反编译代码看到
// 判断如果当前值在缓存取整范围内就直接用缓存对象,不在就创建
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
private static class IntegerCache {
static final int low = -128;
static final int high;
static final Integer cache[];
static {
//可以设置最大值 通过-XX:AutoBoxCacheMax=size修改
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循环创建缓存
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() {}
}
总结
Intege通过自动装箱引发缓存,缓存的默认范围是-128到127,可通过-XX:AutoBoxCacheMax=size 修改最大值。其他的整数类型也有缓存: ByteCache用于缓存Byte对象,ShortCache用于缓存Short对象,LongCache用于缓存Long对象。但是只有Integer可以修改范围,其他的都是固定范围。除了整数之外,CharacterCache用于缓存Character对象,固定范围是0~127。