当自己没有手动new一个对象的时候,系统会自动调用Integer.valueOf(num)方法自动帮你装箱
打开valueOf方法显示如下代码
privatestaticclassIntegerCache {staticfinalint low = -128;
staticfinalint high;
staticfinal Integer cache[];
static {
// high value may be configured by propertyint 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;
}
privateIntegerCache() {}
}
publicstatic Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
returnnew Integer(i);
}
由以上代码可知low的值为-128,high的值等于h等于127,如果 (i >= IntegerCache.low && i <= IntegerCache.high),
这时会返回cache数组中的一个对象,否则会创建一个新的对像返回去,如果系统封装的两个相等数,
且都在IntegerCache.low=-128 与 IntegerCache.high=127范围内,这时会返回Cache数组中相同角标内的内容(对象),
当在这个范围内时,系统早已存在一个数组,数组长度为(high - low)的值,即2^8,
根据代码for(int k = 0; k < cache.length; k++){ cache[k] = new
Integer(j++);},j=low=-128,可以看出下标从0开始一直到255,分别保存着之-128到127的对象,即下标
为255的数里保存的对象的值是127,再根据publicstatic Integer valueOf(int
i)得到i的值,由return IntegerCache.cache[i + (-IntegerCache.low)]可知
返回去的的数组下标为i + (-IntegerCache.low),假设i是127,则127+(-128)得255
即cache数组的下标为255中的内容,即为要返回去的内容,内容为 cache[k] = new
Integer(j++),即new Integer(127);当再封装一个127的时候,返回的仍然是这个
new Integer(127),所以地址相同,即不同引用指向同一个对象,所已结果为true