Java 自动装箱,拆箱

什么时候会进行装箱操作 Integer.valueof()

Integer i=100;

什么时候进行拆箱 Integer.intValue( )

如果其中有一个操作数是表达式(即包含算术运算)则比较的是数值(即会触发自动拆箱的过程),例如 a+b

Integer.valueof()中的cache问题

public static Integer valueOf(int i) {
        if(i >= -128 && i <= IntegerCache.high)
            return IntegerCache.cache[i + 128];
        else
            return new Integer(i);
    }

如果数值在[-128,127]之间,便返回指向IntegerCache.cache中已经存在的对象的引用

==的比较问题

当 “==”运算符的两个操作数都是 包装器类型的引用,则是比较指向的是否是同一个对象,而如果其中有一个操作数是表达式(即包含算术运算)则比较的是数值(即会触发自动拆箱的过程)。

例如:

        Integer a = 1;
        Integer b = 2;
        Integer c = 3;
        Integer d = 3;
        Integer e = 321;
        Integer f = 321;
        Long g = 3L;
        Long h = 2L;

        System.out.println(c==d);---------------true      因为[-128,127]区间,对象相同
        System.out.println(e==f);---------------false     区间原因
        System.out.println(c==(a+b));-----------true      包含运算符,拆箱比较值
        System.out.println(c.equals(a+b));------true      先拆箱(a+b),再装箱
        System.out.println(g==(a+b));-----------true      区间缓存
        System.out.println(g.equals(a+b));------false     对象类型不同
        System.out.println(g.equals(a+h));------true      a+h 向上转换成long类型,再装箱
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值