自动拆装箱

    集合被设计为泛型类,牵扯泛型边界擦除,所以不能存储基本类型,而只能存储对象的引用。有时候我们需要将一个整型或者浮点型的基本类型存入集合之中,只能使用基本类型的包装器类。每一个基本类型都会对应一个包装器类,如下所示:

基本类型包装类
byteByte
shortShort
longLong
intInteger
doubleDouble
floatFloat
charCharacter
booleanBoolean

    对象的包装类和String类一样,都是采用final修饰的类,称之为不可变类,有如下特性:

  • 包装器类一旦被构造,就不可以再更改包装在其中的值;
  • 不能定义包装类的子类,final修饰的类不可被继承;

    包装类到基本类型之间的相互转换被称之为自动拆装箱。

1. 自动装箱操作

    自动装箱操作发生在基本类型转换为包装类的过程之中。如:

ArrayList<Integer> list = new ArrayList<>();
list.add(123);

Arraylist被定义为Integer类型,而进行add操作时入参为int类型,这其中就牵扯装箱操作,执行add操作之前实际上先将int类型的数据包装为Integer类型,list.add(123)实际执行流程如下:

 1. Integer temp =Integer.valueOf(3);
 2. list.add(temp);

    我们可以看到,装箱操作实际底层调用了Integer类的valueOf()方法,而这一个方法又决定了Integer的另一重要特性 —— 缓存数组

vlaueOf具体实现以及核心方法如下:

    //IntegerCache.low为-127,IntegerCache.high为+127
    public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }
    
    //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");
            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() {}
    }

    从value方法我们可以看到,valueOf方法包装的int值在不同的数值范围内具有不同的包装方法,如果在-127~127之中,则直接从Integer的缓存数组中取,如果超过这个范围就直接重新创建Integer对象。两者的区别就在于是否引用的是同一个地址的对象。如下:

    public static void main(String[] args) {

        Integer a = 127;
        Integer b = 127;
        System.out.println("范围之内:" +  (a==b));

        Integer a2 = 128;
        Integer b2 = 128;
        System.out.println("范围之外:" +  (a2==b2));
    }
    
输出结果:
  范围之内:true
  范围之外:false

    很明显,如果传入的int值在-127~127之中,两个引用指向的地址相同,说明引用的是同一个对象,此对象存在于Integer的缓存数组中。传入值在此范围之外,两个引用指向的不是同一地址空间,说明创建了两个对象。自动装箱操作的执行要求boolean、byte以及char 的取值小于等于127,介于-128~127之间的short和int会被包装到固定的对象中,也就是不重新创建对象,超过此范围的则直接重新创建包装类对象。而且包装类属于对象,允许初始化为null,初始化为null时进行拆箱操作会抛出空指针异常。

2. 拆箱操作

    从包装类转换为基本类型的过程会引起拆箱操作,如int n = list.get(i)。同样,拆箱操作实际上也可以分为两步来执行:

1. Integer tmp = list.get(i);
2. int n = tmp.intValue();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值