深入理解java虚拟机之自动装箱

从演示代码开始分析:

public class Autoboxing {
    public static void main(String[] args){
        Integer a = 1;
        Integer b = 2;
        Integer c = 3;
        Integer d = 3;
        Integer e = 321;
        Integer f = 321;
        Long g = 3L;
        System.out.println(c == d);//true  -128 ~ 127之间的值从IntegerCache 的cache数组中取值,拿到的是同一个对象 cache[129]
        System.out.println(e == f);//false 大于127、小于-128的值 通过new Integer()来创建对象
        System.out.println(c == (a + b));//true  == 包装类在遇到算术运算符会自动拆箱
        System.out.println(c.equals(a + b));// true equals方法会同时比较类型和值是否相同
        System.out.println(g == (a + b));//true  == 包装类在遇到算术运算符会自动拆箱
        System.out.println(g.equals(a + b));//false 包装类的equals方法不处理数据转型的关系
    }
}

分析:

在程序执行 Integer a =1这句代码时,会进行自动装箱,调用 Integer.valueOf()方法,查看Integer.valueOf方法源代码:

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

其中,IntegerCache.low = -128, IntegerCache.high = 127;因此,对于Integer类型的数字,如果数字大于等于-128且小于等于127,自动装箱返回的是IntegerCache.cache[]数组对象;如果数字大于127且小于等于2^32-1 或者 大于等于-2^32小于-128,自动装箱返回一个Integer对象。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值