new Integer(123) 每次都會(huì)新建一個(gè)對(duì)象;
Integer.valueOf(123) 會(huì)使用緩存池中的對(duì)象,多次調(diào)用會(huì)取得同一個(gè)對(duì)象的引用。
Integer x = new Integer(123);
Integer y = new Integer(123);
System.out.println(x == y); // false
Integer z = Integer.valueOf(123);
Integer k = Integer.valueOf(123);
System.out.println(z == k); // true
valueOf() 方法的實(shí)現(xiàn)比較簡(jiǎn)單,就是先判斷值是否在緩存池中,如果在的話就直接返回緩存池的內(nèi)容。
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
在 Java 8 中,Integer 緩存池的大小默認(rèn)為 -128~127。
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;
}
編譯器會(huì)在自動(dòng)裝箱過(guò)程調(diào)用 valueOf() 方法,因此多個(gè)Integer實(shí)例使用自動(dòng)裝箱來(lái)創(chuàng)建并且值相同,那么就會(huì)引用相同的對(duì)象。
Integer m = 123;
Integer n = 123;
System.out.println(m == n); // true
基本類型對(duì)應(yīng)的緩沖池如下:
在使用這些基本類型對(duì)應(yīng)的包裝類型時(shí),就可以直接使用緩沖池中的對(duì)象。
其他介紹
創(chuàng)新互聯(lián)www.cdcxhl.cn,專業(yè)提供香港、美國(guó)云服務(wù)器,動(dòng)態(tài)BGP最優(yōu)骨干路由自動(dòng)選擇,持續(xù)穩(wěn)定高效的網(wǎng)絡(luò)助力業(yè)務(wù)部署。公司持有工信部辦法的idc、isp許可證, 機(jī)房獨(dú)有T級(jí)流量清洗系統(tǒng)配攻擊溯源,準(zhǔn)確進(jìn)行流量調(diào)度,確保服務(wù)器高可用性。佳節(jié)活動(dòng)現(xiàn)已開啟,新人活動(dòng)云服務(wù)器買多久送多久。