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)比較簡單,就是先判斷值是否在緩存池中,如果在的話就直接返回緩存池的內(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)裝箱過程調(diào)用 valueOf() 方法,因此多個(gè)Integer實(shí)例使用自動(dòng)裝箱來創(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è)提供香港、美國云服務(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ù)器買多久送多久。
分享題目:《Java架構(gòu)筑基》從Java基礎(chǔ)講起——基礎(chǔ)類型緩存池概念-創(chuàng)新互聯(lián)
轉(zhuǎn)載來源:http://chinadenli.net/article16/dghcgg.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供App設(shè)計(jì)、服務(wù)器托管、域名注冊(cè)、關(guān)鍵詞優(yōu)化、網(wǎng)站設(shè)計(jì)、企業(yè)網(wǎng)站制作
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容