1.首先是在valueOf()中出現(xiàn)了對(duì)緩存策略的使用,通過IntegerCache可知當(dāng)-128<=i<=127(默認(rèn))時(shí)候使用了緩存策略。也就是i在范圍內(nèi)的話就從內(nèi)存中取出返回,如果不在范圍內(nèi)就new一個(gè)Integer對(duì)象。
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
2.IntegerCache是Integer的一個(gè)靜態(tài)內(nèi)部類:
1)如果設(shè)置了java.lang.IntegerCache.high,就使用這個(gè)值,如果沒有設(shè)置就使用127,java.lang.IntegerCache.high這個(gè)值是通過JVM參數(shù)改變的,在java程序執(zhí)行的時(shí)候加上 -XX:AutoBoxCacheMax=<size> 的參數(shù)即可。
2)使用了斷言assert;
3)其實(shí)所謂的在內(nèi)存中取值,就是在數(shù)組中,可以看出,Integer的值是被存在了cache數(shù)組中的。
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() {}
}