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);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章