/** * Returns an {@code Integer} instance representing the specified * {@code int} value. If a new {@code Integer} instance is not * required, this method should generally be used in preference to * the constructor {@link #Integer(int)}, as this method is likely * to yield significantly better space and time performance by * caching frequently requested values. * * This method will always cache values in the range -128 to 127, * inclusive, and may cache other values outside of this range. * * @param i an {@code int} value. * @return an {@code Integer} instance representing {@code i}. * @since 1.5 */ publicstatic Integer valueOf(int i){ //断言 high>=127 assert IntegerCache.high >= 127; //判断传入参数 i 是否在范围之间 //如果是,返回 IntegerCache.cache 数组中索引为 i + (-IntegerCache.low) 的元素 //如果不是,返回一个新的 Integer 对像 if (i >= IntegerCache.low && i <= IntegerCache.high) return IntegerCache.cache[i + (-IntegerCache.low)]; returnnew Integer(i); }
static { // high value may be configured by property int h = 127; //大概是从 jvm 中取出Integer对象缓冲池的high值,没有仔细研究 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赋值 high = h;
//创建数组对象赋值给 cache //大小为 (high-low)+1 //类型为 Integer cache = new Integer[(high - low) + 1]; int j = low; //给 cache 中的元素赋值,满足 cache[i]=i+low for(int k = 0; k < cache.length; k++) cache[k] = new Integer(j++); }