新手學JAVA(五)----深入剖析JAVA拆裝箱

來源:互聯網
上載者:User

標籤:java   裝箱   拆箱   拆裝箱   

先來看一段代碼:

public class Main{    public static void main(String[] args){        Integer num1 = 100;        Integer num2 = 100;        Integer num3 = 200;        Integer num4 = 200;        ‘‘‘//輸出結果‘‘‘        System.out.println(num1==num2);        System.out.println(num3==num4);    }}

猜猜結果是什嗎?
很多人都會認為結果全為true,但結果去不是這樣的

truefalse

為什麼是這樣的結果?如果用記憶體來解釋結果的話,num1和num2指向的是同一個對象,而num3和num4則指向的確是不同的對象。接下來就告訴你為什麼,看一看Integer類型的valueof方法的源碼:

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

其中IntegerCache的實現:

‘‘‘// IntegerCache,一個內部類,注意它的屬性都是定義為static final‘‘‘    private static class IntegerCache {        static final int high; ‘‘‘//緩衝上界,暫為null‘‘‘        static final Integer cache[]; ‘‘‘//緩衝的整型數組‘‘‘        ‘‘‘// 塊,為什麼定義為塊‘‘‘        static {            final int low = -128; ‘‘‘// 緩衝下界,不可變了。只有上界可以改變‘‘‘            ‘‘‘// high value may be configured by property‘‘‘            ‘‘‘// h值,可以通過設定jdk的AutoBoxCacheMax參數調整(以下有解釋),自動緩衝區間設定為[-128,N]。注意區間的下界是固定‘‘‘            int h = 127;            if (integerCacheHighPropValue != null) {                ‘‘‘// Use Long.decode here to avoid invoking methods that‘‘‘                ‘‘‘// require Integer‘s autoboxing cache to be initialized‘‘‘                // 通過解碼integerCacheHighPropValue,而得到一個候選的上界值‘‘‘                int i = Long.decode(integerCacheHighPropValue).intValue();                ‘‘‘// 取較大的作為上界,但又不能大於Integer的邊界MAX_VALUE‘‘‘                i = Math.max(i, 127);                     ‘‘‘// Maximum array size is Integer.MAX_VALUE‘‘‘                h = Math.min(i, Integer.MAX_VALUE - -low);            }            high = h; ‘‘‘//上界確定‘‘‘            ‘‘‘// 就可以建立緩衝塊,注意緩衝數組大小‘‘‘            cache = new Integer[(high - low) + 1]; //            int j = low;            for(int k = 0; k < cache.length; k++)                cache[k] = new Integer(j++); ‘‘‘// -128到high值逐一分配到緩衝數組‘‘‘        }        private IntegerCache() {}    }

通過這兩段代碼可以看出,在通過valueof方法建立Integer類型對象時,取值範圍為[-128,127],數值在這個區間裡,指標指向IntegerCache.cache中已經存在的對象引用,當數值超出這個範圍,就會建立一個新的對象。

有一點需要注意的是,並不是所有的類型都是這個範圍,看Double類型:

public class Main{    public static void main(String[] args){        Double i1 = 100.0;        Double i2 = 100.0;        Double i3 = 200.0;        Double i4 = 200.0;        System.out.println(i1==i2);        System.out.println(i3==i4);    }}

最終的輸出結果:

falsefalse

具體為什麼回事這樣的結果,大夥可以去看看原始碼中Double valueof方法的實現,其和Integer valueof方法不同,是因為在某個範圍內的整型數值的個數是有限的,而浮點數卻不是。

注意,Integer、Short、Byte、Character、Long這幾個類的valueOf方法的實現是類似的。
Double、Float的valueOf方法的實現是類似的。

拉下了一個,Boolean類型的結果有兩個True or False。直接看原始碼:

public static Boolean valueOf(boolean b) {        return (b ? TRUE : FALSE);    }

而其中的TRUE和FALSE是這樣定義的:

public static final Boolean TRUE = new Boolean(true);‘‘‘/** ‘‘‘‘‘‘* The <code>Boolean</code> object corresponding to the primitive ‘‘‘‘‘‘* value <code>false</code>. ‘‘‘‘‘‘*/‘‘‘public static final Boolean FALSE = new Boolean(false);

新手學JAVA(五)----深入剖析JAVA拆裝箱

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.