各位老师好,小弟在学习 JDK7 学习笔记的过程中,对于装箱的内幕这一块,有一些疑惑。
参看了valueOf以及IntegerCache的源代码:
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) -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++);
}
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在生成之初,就已经将从low至high的每个Integer实例进行创建,并依次放入数组当中。
之后,需要用到valueOf时,会做数值判断,只要值介于low和high之间,就直接返回cache中的对象,而不会调用构造器。
只有超出范围时,才会调用构造器来创建新实例。
那么,是不是说,只要数字在Cache的范围内,任何名牌都会指向同一个实例,也就是判断 == 的话,都会返回true? |