本帖最后由 隋营营 于 2012-5-7 21:20 编辑
这种问题可以直接看 Integer 类的源代码:
Integer类中有一个内部类IntegerCache,它的实现很能说明问题!
/**
* Cache to support the object identity semantics of autoboxing for values between
* -128 and 127 (inclusive) as required by JLS.
*
* The cache is initialized on first usage. The size of the cache
* may be controlled by the -XX:AutoBoxCacheMax=<size> option.
* During VM initialization, java.lang.Integer.IntegerCache.high property
* may be set and saved in the private system properties in the
* sun.misc.VM class.
*/
private static class IntegerCache {
static final int low = -128;
static final int high;
static final Integer 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) {
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++);
}
private IntegerCache() {}
}
/***
*......................................................................
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);
}
/**
*.......................................
IntegerCache类有一个静态的Integer数组,在Integer类加载时就创建了一个Integer对象(数值在-128~127之间,最大值可以根据property设定),保存在cache数组中。
若valueOf()方法被调用,若Integer对象的值在-128 到 127 之间,就直接在cache缓存数组中去取!
个人猜想之所以不把所有字节都缓存起来是为了节约内在空间!
非常感谢对认识不到的地方给予指正!
|