您好,登錄后才能下訂單哦!
Integer 的部分源碼:
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;
}
示例1:
Integer i1=40;
//Java 在編譯的時(shí)候會(huì)直接將代碼封裝成 Integer i1=Integer.valueOf(40);從而使用常量池中的對(duì)象。
Integer i2 = new Integer(40);
//創(chuàng)建新的對(duì)象。
System.out.println(i1==i2);//輸出false
示例2:Integer有自動(dòng)拆裝箱功能
Integer i1 = 40;
Integer i2 = 40;
Integer i3 = 0;
Integer i4 = new Integer(40);
Integer i5 = new Integer(40);
Integer i6 = new Integer(0);
System.out.println("i1=i2 " + (i1 == i2)); //輸出 i1=i2 true
System.out.println("i1=i2+i3 " + (i1 == i2 + i3)); //輸出 i1=i2+i3 true
//i2+i3得到40,比較的是數(shù)值
System.out.println("i1=i4 " + (i1 == i4)); //輸出 i1=i4 false
System.out.println("i4=i5 " + (i4 == i5)); //輸出 i4=i5 false
//i5+i6得到40,比較的是數(shù)值
System.out.println("i4=i5+i6 " + (i4 == i5 + i6)); //輸出 i4=i5+i6 true
System.out.println("40=i5+i6 " + (40 == i5 + i6)); //輸出 40=i5+i6 true
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。