Java裝箱與拆箱的區別?

認識裝箱和拆箱

裝箱就是自動將基本數據類型轉換爲包裝器類型(int-->Integer);調用方法:Integer的valueOf(int) 方法。

拆箱就是自動將包裝器類型轉換爲基本數據類型(Integer-->int);調用方法:Integer的intValue方法。

在Java SE5之前,如果要生成一個數值爲10的Integer對象,必須這樣進行:

Integer i = new Integer(10);

而在從Java SE5開始就提供了自動裝箱的特性,如果要生成一個數值爲10的Integer對象,只需要這樣就可以了:

Integer i = 10;

 

 

題1:以下代碼會輸出什麼

 

public class Main {
    public static void main(String[] args) {

        Integer i1 = 100;
        Integer i2 = 100;
        Integer i3 = 200;
        Integer i4 = 200;

        System.out.println(i1==i2);
        System.out.println(i3==i4);
    }
}

運行結果:

true
false

輸出結果表明i1和i2指向的是同一個對象,而i3和i4指向的是不同的對象。

爲什麼會出現這樣的結果?

此時只需一看源碼便知究竟,下面這段代碼是Integer的valueOf方法的具體實現:

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

其中IntegerCache類的實現爲:

private static class IntegerCache {
        static final int high;
        static final Integer cache[];

        static {
            final int low = -128;

            // high value may be configured by property
            int h = 127;
            if (integerCacheHighPropValue != null) {
                // Use Long.decode here to avoid invoking methods that
                // require Integer's autoboxing cache to be initialized
                int i = Long.decode(integerCacheHighPropValue).intValue();
                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++);
        }

        private IntegerCache() {}
    }

從這2段代碼可以看出,在通過valueOf方法創建Integer對象的時候,如果數值在[-128,127]之間,便返回指向IntegerCache.cache中已經存在的對象的引用;否則創建一個新的Integer對象。

上面代碼中i1和i2的數值爲100,因此會直接從cache中取已經存在的對象,所以i1和i2指向的是同一個對象,而i3和i4則分別指向不同的對象。

 

題2:以下代碼輸出什麼?

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);
    }
}

運行結果:

false
false

原因:在某個範圍內的整型數值的個數是有限的,而浮點數卻不是。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章