Java包裝類型

Java有8種基本數據類型,每種基本數據類型都提供了一種對應的包裝類型,從 Java 5 開始引入了自動裝箱/拆箱機制,使得二者可以相互轉換。

  • 原始類型: boolean,char,byte,short,int,long,float,double
  • 包裝類型:Boolean,Character,Byte,Short,Integer,Long,Float,Double
  • 裝箱:將基本類型用它們對應的引用類型包裝起來,調用valueOf()方法, 如:Integer.valueOf();

  • 拆箱:將包裝類型轉換爲基本數據類型,調用xxxValue()方法, 如Integer.intValue();

// 將a自動裝箱爲Integer類型
// 裝箱源碼: Integer.valueOf(int i)
Integer a = 1;
int b = 2;
// 將a拆箱爲int再和b作比較
System.out.println(a == b);

Tips: 如果頻繁拆裝箱的話,也會嚴重影響系統的性能。應該儘量避免不必要的拆裝箱操作。

基本數據類型的包裝類型的大部分都用到了緩存機制來提升性能。 Byte,Short,Integer,Long 這 4 種包裝類默認創建了數值 [-128,127] 的相應類型的緩存數據,Character 創建了數值在 [0,127] 範圍的緩存數據,Boolean 直接返回 True or False。兩種浮點數類型的包裝類 Float,Double 並沒有實現緩存機制。例如:

// 用到緩存
Integer a = 50;
Integer b = 50;
// true
System.out.println(a == b);

// 沒有用緩存
Integer c = 150;
Integer d = 150;
// false
System.out.println(c == d);

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

Boolean緩存:

public static final Boolean TRUE = new Boolean(true);
public static final Boolean FALSE = new Boolean(false);
public static Boolean valueOf(boolean b) {
    return (b ? TRUE : FALSE);
}

Character 緩存源碼:

public static Character valueOf(char c) {
    if (c <= 127) { 
      return CharacterCache.cache[(int)c];
    }
    return new Character(c);
}
private static class CharacterCache {
    private CharacterCache(){}
    static final Character cache[] = new Character[127 + 1];
    static {
        for (int i = 0; i < cache.length; i++)
            cache[i] = new Character((char)i);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章