包装类的缓存
包装类缓存的问题:
整型、char类型所对应的包装类,在自动装箱时,对于-128~127之间的值会进行缓存处理,目的是提高效率。
缓存的原理:如果数据在-128~127区间,那么类加载时就已经为该区间的每一个数值创建好了对象,并将这256个对象存放在名为cache的数组中。每当自动装箱过程发生时(或手动调用valueOf()时),就会先判断数据是否在该区间,如果在则直接获取数组中对应的包装类对象的引用,如果不在就通过new调用包装类的构造方法来创建对象。
//包装类的缓存区间为[-128,127]的数字,实际就是系统初始化的时候已经创建了一个[-128,127]之间的一个缓存数组
//当我们调用valueOf()的时候,首先检查是否在[-128,127]之间,如果在直接从缓存数组中拿出已经创建好的对象
//如果没有在这个范围中就重新创建一个新的Integer对象
Integer a = -128;//Integer a = Integer.valueOf(-128);
Integer b = -128;
System.out.println(a==b);//检测是否是一个对象。返回true
System.out.println(a.equals(b));//检测对象内容是否一样 返回true
Integer a1 = 1258;
Integer b1 = 1258;
System.out.println(a1==b1);//因为a1和b1不在缓存范围中所以就会重新创建一个对象,返回false
System.out.println(a1.equals(b1));//返回true
/***********************************************************/
//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);//创建新的Integer对象
}
//Integer的静态内部类IntegerCache
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() {}
}