类Integer
具有缓存,它缓存Integer
值。因此,如果我使用方法valueOf
或拆箱,新值将不会被实例化,而是从缓存中获取。
我知道默认缓存大小为127
,但可以根据VM设置进行扩展。我的问题是:这些设置中默认的缓存大小是多少,我可以操纵这个值吗?这个值是否取决于我使用的VM(32位还是64位)?
我现在正在调整遗留代码,可能需要将int转换为Integer。
澄清:以下代码是我在Java源代码中找到的
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) {
int i = parseInt(integerCacheHighPropValue);
i = Math.max(i, 127);
// Maximum array size is Integer.MAX_VALUE
h = Math.min(i, Integer.MAX_VALUE - (-low));
}
high = h;
cache = new Integer[(high - low) + 1];
int j = low;
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);
}
private IntegerCache() {}
}
public static Integer valueOf(int i) {
assert IntegerCache.high >= 127;
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
所以我认为缓存是可配置的。
java.lang.Integer.IntegerCache.high
来设置不同的限制。源代码中已经有了所有的内容。 - Marko Topolnikhigh
可以配置,但low
却是硬编码的。 - Max Nanasy