Integer a = new Integer(125);
Integer b = new Integer(125);
// false
System.out.println(a == b);
Integer c = Integer.valueOf(125);
Integer d = Integer.valueOf(125);
// true
System.out.println(c == d );這裡不討論包裝類型間的相等判斷應該用equals,而不是'==';
源碼解讀public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}Integer.valueOf() 方法的實現比較簡單,第一步先判斷值是否在緩存池中,如果在的話就直接返回緩存池的內容。
那麼,在 Java 8 中 Integer 中緩存池默認大小是多少呢?答案是 -128~127;編譯器會在緩衝池範圍內的基本類型自動裝箱過程調用 valueOf() 方法,因此多個 Integer 實例使用自動裝箱來創建並且值相同,那麼就會引用相同的對象。
Integer a = 125;
Integer b = 125;
// true
System.out.println(a == b);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) {
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;
}
private IntegerCache() {}
}所以我們在使用 Int 類型對應的包裝類型時,就可以直接使用緩衝池中的對象。
結束語何為目的?人生根本沒有目的,何況工作呢。
- END -