自動裝箱與自動拆箱

1. 緩存機制

1. 現(xiàn)象
        Integer c = 3;
        Integer d = 3;
        Integer e = 321;
        Integer f = 321;
        
        System.out.println(c == d);//true
        System.out.println(e == f);//false
2. 解釋

Integer c = 3;這個操作實際上是自動裝箱的操作,真實的是Integer c = Integer.valueOf(3);
看了一下Integer.valueOf源碼發(fā)現(xiàn):

class Integer{
    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() {}
    }

    public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }
}

可以看到默認(rèn)情況下:Integer有一個static代碼塊,目的是初始化一個長度為256的Integer對象數(shù)組,當(dāng)valueOf傳入值在[-128, 127]區(qū)間時,就會返回這個數(shù)組的一個元素。
所以c和d是指向同一個對象。而e和f是不同的對象。

3. 結(jié)論
  • 對于Boolean、Byte、Character、Short、Integer、Long六種基本類型,
    對于一個字節(jié)以內(nèi)的值-128到127(Boolean只有true和false)都實現(xiàn)了緩存機制。
    不在此范圍的數(shù)才在對應(yīng)的valueOf()方法中new出一個新的對象。
  • 但是對于Double和Float類型的浮點數(shù)據(jù),在-128到127之間除了256個整數(shù)外還有無數(shù)的小數(shù),
    故java中沒有實現(xiàn)Double和Float中一些數(shù)的緩存。
    所以,對于Double和Float的自動裝箱,都是new出新的對象。

2. 自動裝箱與自動拆箱的時機

1. 自動裝箱
Integer a = 1;//自動裝箱 其中調(diào)用的是Integer.valueOf函數(shù)

自動裝箱很簡單。

2. 自動拆箱
        int i1 = new Integer(2);//(1)自動拆箱 其實調(diào)用的就是i1.intValue()函數(shù)

        Integer i2 = 2;
        System.out.println(i2 == 2);//(2)true i2自動拆箱

        Integer i3 = 3;
        Long i4 = 5L;
        System.out.println(i4 == (i2 + i3));//(3)true 算術(shù)運算符會導(dǎo)致自動拆箱

        Integer i5 = 321;
        Integer i6 = 321;
        System.out.println(i5 == i6);//(4)false ==不會進行自動拆箱

        System.out.println(i4.equals(i2+i3));//(5)false equals方法不會進行類型轉(zhuǎn)換

自動拆箱的時機:

  • 當(dāng)遇到int i = Integer的賦值語句時
  • 當(dāng)==兩端一個是包裝類,一個是基礎(chǔ)數(shù)據(jù)時,包裝類會自動拆箱
  • 拆箱只發(fā)生在非==時,即兩個包裝類進行算術(shù)運算都是自動拆箱(解釋了3和4的現(xiàn)象)
  • 包裝類的equals方法不會進行類型轉(zhuǎn)換。(解釋了5的現(xiàn)象)

注意上面說的自動拆箱的時機適用于所有包裝類(Double/Float等)
舉個例子:

        Integer i2 = 2;
        Integer i3 = 3;
        Double d1 = 5.0;
        System.out.println(d1 == i2+i3);//true
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容