/** * This method will always cache values in the range -128 to 127, * inclusive, and may cache other values outside of this range. * 如果传入的数值在缓存的-127和128之间,那么都会在cache中,否则的话,会new出新的对象,这也是为什么100==100为true,1000==1000为false * @param i an {@code int} value. * @return an {@code Integer} instance representing {@code i}. * @since 1.5 */ publicstatic Integer valueOf(int i){ assert IntegerCache.high >= 127; if (i >= IntegerCache.low && i <= IntegerCache.high) return IntegerCache.cache[i + (-IntegerCache.low)]; returnnew Integer(i); }
/** 只要在-128-127,使用 == 判断是可以的,不再这个范围就不能使用==,需要使用equqls * Cache to support the object identity semantics of autoboxing for values between * -128 and 127 (inclusive) as required by JLS. * */
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) -1); } high = h;
cache = new Integer[(high - low) + 1]; int j = low; for(int k = 0; k < cache.length; k++) cache[k] = new Integer(j++); }