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;
/*//意味着可以通过JVM参数java.lang.Integer.IntegerCache.high来设置缓存的最大值*/
String integerCacheHighPropValue =
sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
/*如果设置了最大值*/
if (integerCacheHighPropValue != null) {
try {
int i = parseInt(integerCacheHighPropValue);
/*最大值和127作比较,即即使我们设置了最大值,如果小于127,也不会生效*/
i = Math.max(i, 127);
// Maximum array size is Integer.MAX_VALUE
/*h为数组的最大值,这里是考虑边界情况,如果在jvm参数里设置的值超过边界才会执行,一般都是i*/
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;
/*给cache数组中赋值*/
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);
// range [-128, 127] must be interned (JLS7 5.1.7)
/*断言:即assert后的的布尔表达式永真才不报错,即保证high最小也得是127,要不然我就抛异常,其实还是边界处理*/
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);
}
在Java中,Integer 类型的缓存数组是一个包含了固定范围的整数对象的数组。该数组存储了在一定范围内的整数值对应的 Integer 对象,以便在需要时可以重复使用,减少对象的创建和内存消耗。
具体来说,Integer 类型的缓存数组默认范围是 -128 到 127,总共包含了 256 个元素。这个范围可以通过系统属性 java.lang.Integer.IntegerCache.high 来调整,但默认情况下是不可更改的。
当使用 Integer.valueOf(int) 方法创建 Integer 对象时,如果传入的整数值在缓存数组范围内,方法会直接返回缓存数组中对应位置的对象。这样就避免了创建新的对象,提高了性能和节省了内存。
需要注意的是,缓存数组中的对象是不可变的(Immutable),即它们的值不可修改。因此,任何对缓存数组中对象的修改操作都会导致创建一个新的对象。
对于超出缓存数组范围的整数值,例如超过 127 或小于 -128,Integer.valueOf(int) 方法会创建一个新的 Integer 对象,并返回该对象的引用。
这种缓存机制在一定程度上提高了性能和内存利用率,特别是在频繁使用范围内整数值的场景中。但需要注意,使用缓存数组时,应避免对缓存对象进行修改,以免引发意外的结果。
Java中的Integer缓存数组默认存储-128到127的Integer对象,通过Integer.valueOf(int)方法可复用这些对象,提高性能。超出范围的值会新建对象。缓存对象是不可变的,避免修改以防止意外。
932





