public static Integer valueOf(int i) { //判断i是否在-128和127之间,存在则从IntegerCache中获取包装类的实例,否则new一个新实例 if (i >= IntegerCache.low && i <= IntegerCache.high) return IntegerCache.cache[i + (-IntegerCache.low)]; return new Integer(i); }
//使用亨元模式,来减少对象的创建(亨元设计模式大家有必要了解一下,我认为是最简单的设计模式,也许大家经常在项目中使用,不知道他的名字而已) private static class IntegerCache { static final int low = -128; static final int high; static final Integer cache[];
//静态方法,类加载的时候进行初始化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; }
//boolean原生类型自动装箱成Boolean public static Boolean valueOf(boolean b) { return (b ? TRUE : FALSE); }
//byte原生类型自动装箱成Byte public static Byte valueOf(byte b) { final int offset = 128; return ByteCache.cache[(int)b + offset]; }
//byte原生类型自动装箱成Byte public static Short valueOf(short s) { final int offset = 128; int sAsInt = s; if (sAsInt >= -128 && sAsInt <= 127) { // must cache return ShortCache.cache[sAsInt + offset]; } return new Short(s); }
//char原生类型自动装箱成Character public static Character valueOf(char c) { if (c <= 127) { // must cache return CharacterCache.cache[(int)c]; } return new Character(c); } //int原生类型自动装箱成Integer public static Integer valueOf(int i) { if (i >= IntegerCache.low && i <= IntegerCache.high) return IntegerCache.cache[i + (-IntegerCache.low)]; return new Integer(i); }
//int原生类型自动装箱成Long public static Long valueOf(long l) { final int offset = 128; if (l >= -128 && l <= 127) { // will cache return LongCache.cache[(int)l + offset]; } return new Long(l); }
//double原生类型自动装箱成Double public static Double valueOf(double d) { return new Double(d); }
//float原生类型自动装箱成Float public static Float valueOf(float f) { return new Float(f); }