Java装箱与拆箱

装箱就是自动将基本数据类型转换为包装类型(int => Integer);调用方法Integer的valueOf(int)方法
拆箱就是自动将包装类型转换为基本数据类型(Integer => Int;调用Integer方法intValue方法
  1. 程序块输出结果
    public static void main(String[] args) {

        //2.java自动装箱、拆箱
        Integer i1 = 100;
        Integer i2 = 100;
        Integer i3 = 200;
        Integer i4 = 200;

        System.err.println(i1 == i2);
        System.err.println(i3 == i4);

    }

输出结果:

true
false

分析:i1和i2指向的是同一个对象,i3和i4指向的是不同的对象。Interger的valueOf方法的具体实现:

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

其中IntergerCache类的源码为:
在这里插入图片描述

调用Interger的valueOf方法时,如果i在-128到127之间,就会从初始化的cache数组中取出对应的Integer对象;如果不再这个区间,就会执行new Interger(i),创建一个新的对象。

所以i1和i2是从cache数组中取出已经存在的对象,i1和i2指向的是同一个对象,i3和i4指向的是不同的对象。

  1. 程序块:
    public static void main(String[] args) {

        Double i1 = 100.0;
        Double i2 = 100.0;
        Double i3 = 200.0;
        Double i4 = 200.0;
        System.err.println(i1 == i2);
        System.err.println(i3 == i4);
    }

输出结果:

false
false`

分析:整数在上述范围内个数是有限的,浮点数不是这样的。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值