Integer.valueOf(int i)
方法包含assesrt檢查IntegerCache更多或等於127冗餘斷言
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);
}
緩存實現看起來像這樣
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++);
}
,所以你可以通過傳遞屬性值來增加緩存大小。但是,實現不會允許您將緩存大小設置爲低於127(或它?)。那麼他們爲什麼要在Integer.valueOf()
中發表斷言。開發人員不相信自己的實現嗎? 據我所知,如果緩存低於127 Integer.valueOf(int i)
會返回錯誤的價值,但這種事情不可能發生......
是否有必要在那裏斷言?
問題是什麼? – Ilya