先看一段代碼
public static void main(String[] args) {
Integer a = 100, b = 100, c = 600, d = 600;
System.out.println(a == b);
System.out.println(c == d);
}
結果是
查看源碼得知,以上四個變量都進行了自動裝箱
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
而且,當參數值在IntegerCache
範圍之內時,返回的是已有的對象
看一下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 integerCacheHigh