java自动装箱拆箱原理

java自动装箱拆箱原理

看了很多博主都没写原理,只是浅显地说了自动装箱拆箱的含义,我就把这个必须知道的知识写一下吧

1.自动装箱

以int -> Integer为例,Integer integer = 1;
编译器编译过程中自动调用这个方法:

Integer integer = Integer.valueOf(1);

将int转换成Integer对象

注意
默认情况下,
装箱时int在[-128,127]范围时从IntegerCache类中的chche[]数组中返回一个现有的Integer对象
超过范围则返回一个新Integer对象

//Integer的valueOf方法
public static Integer valueOf(int i) {
        assert IntegerCache.high >= 127;
        if (i >= IntegerCache.low && i <= IntegerCache.high)
        	//这里数组下标从0开始,所以索引要加128
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

(拓展)再注意一点:
缓存Integer对象的范围也是可以配置的,这是IntegerCache的静态代码块:

  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) {
                int i = parseInt(integerCacheHighPropValue);
                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++);
        }

2.自动拆箱

和装箱类似,自动调用Integer对象的intValue()方法;
如:int i = integer;编译时会自动调用:

int i = integer.intValue();

3.注意事项

(1)相同int经过自动装箱的Integer对象有可能是同一对象也可能不是,所以对Integer比较时应用equals()方法.
(2)int的默认值为0,而Integer引用默认为null.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值