我所理解的JDK自動裝箱和拆箱

1,什麼是自動裝箱和拆箱?
Java中有8種基本數據類型:1字節=8bit(位)java

  • 整形:byte(1字節) short(2字節) int(4字節) long(8字節)
  • 浮點型:float(4字節) double(8字節)
  • 字符型:char(2字節)
  • 布爾型boolean(JVM未規定,Hospot採用4字節)

對應的包裝類型爲:Byte、Short、Integer、Long、Float、Double、Character、Boolean數組

包裝類型的對象存在與堆空間中。基本數據類型的存在是爲了更有效率地方便計算。緩存

  JDK1.5以前,這兩種類型不能直接轉換。從JDK1.5開始,爲了方便開發,開始支持這兩種類型直接轉換。從基本數據類型到包裝類型稱爲裝箱,從包裝類型到基本數據類型稱爲拆箱code

Integer i = 3; // 自動裝箱
int a = i; // 自動拆箱

2,自動裝箱和拆箱的源碼實現
先看int和Integer的轉換:orm

Integer類有個屬性: private final int value;對象

自動拆箱會調用Integer.intValue(),源碼:開發

public int intValue() {
        return value;
    }

自動裝箱會調用Integer.valueOf(),源碼:get

public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high) // 若是i在IntegerCache.low和IntegerCache.high的範圍內
            return IntegerCache.cache[i + (-IntegerCache.low)]; //返回IntegerCache.cache[]中的Integer數據
        return new Integer(i); // 若是不在緩存範圍內,新建一個Integer對象
    }

IntegerCache是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"); // 能夠經過啓動參數-Djava.lang.Integer.IntegerCache.high=127來指定
            if (integerCacheHighPropValue != null) {
                try {
                    int i = parseInt(integerCacheHighPropValue);
                    // 最大值不能小於127
                    i = Math.max(i, 127);
                    // 最大值不能超過Integer.MAX_VALUE=2147483647
                    h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
                } catch( NumberFormatException nfe) {
                    // 若是指定的參數不能轉換爲int類型數據,直接跳過。
                }
            }
            high = h;

            cache = new Integer[(high - low) + 1];
            int j = low;
            for(int k = 0; k < cache.length; k++) // 爲緩存數組賦值
                cache[k] = new Integer(j++);

            assert IntegerCache.high >= 127;
        }

        private IntegerCache() {}
    }

  其餘的整形類型和字符型與此相似,均有緩存。Byte,Short,Long 有固定範圍: -128 到 127。對於 字符型Character, 範圍是 0 到 127。
  除了 Integer 能夠經過參數改變範圍外,其它的都不行。
  自動裝箱時若是是緩存邊界以外的數據,則新建立對象,不然返回緩存中的對象
  浮點型數據沒有緩存。(可能由於浮點型數據沒有範圍。。。)it

布爾型Boolean的裝箱和拆箱源碼: Boolean類有3個屬性:

public static final Boolean TRUE = new Boolean(true);
public static final Boolean FALSE = new Boolean(false);
private final boolean value;

自動裝箱的源碼:

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

自動拆箱的源碼:

public boolean booleanValue() {
        return value;
    }

參考資料:

  1. 以上內容爲筆者平常瑣屑積累,已無從考究引用。若是有,請站內信提示。
相關文章
相關標籤/搜索