溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

詳解Java 虛擬機(jī)(第④篇)——8 種基本類型的包裝類和常量池

發(fā)布時(shí)間:2020-08-08 10:32:22 來(lái)源:ITPUB博客 閱讀:154 作者:無(wú)敵天驕 欄目:軟件技術(shù)

詳解Java 虛擬機(jī)(第④篇)——8 種基本類型的包裝類和常量池

  • Java 基本類型的包裝類的大部分都實(shí)現(xiàn)了常量池技術(shù), 即Byte,Short,Integer,Long,Character,Boolean; 這 5 種包裝類默認(rèn)創(chuàng)建了數(shù)值 [-128,127] 的相應(yīng)類型的緩存數(shù)據(jù), 但是超出此范圍仍然會(huì)去創(chuàng)建新的對(duì)象。
  • 兩種浮點(diǎn)數(shù)類型的包裝類 Float , Double 并沒有實(shí)現(xiàn)常量池技術(shù)。
    valueOf() 方法的實(shí)現(xiàn)比較簡(jiǎn)單,就是先判斷值是否在緩存池中,如果在的話就直接返回緩存池的內(nèi)容。

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
向AI問一下細(xì)節(jié)

免責(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)容。

AI