java的装箱与拆箱

本文详细介绍了Java中装箱和拆箱的概念,以及它们的实现过程。通过示例代码展示了Integer对象在不同数值范围内的装箱和拆箱行为,并通过源码分析解释了为何在-128到127之间Integer对象会共享内存地址,从而导致比较结果为true,而超出此范围则会创建新对象,返回结果为false。此外,还提及了常量池在这一过程中的作用。
摘要由CSDN通过智能技术生成

最近碰到一个题,如下:

public class Main {
    public static void main(String[] args) {
         
        int i1 = 100.0;
        int i2 = 100.0;
        int i3 = 200.0;
        int i4 = 200.0;
         
        System.out.println(i1==i2);
        System.out.println(i3==i4);
    }
}

最后返回结果是:

true
false

仔细了解了一下,学到了一个新概念,就是java的装箱和拆箱。

1.1什么是拆箱和装箱?

Integer a=5;//装箱
int b=a;//拆箱

简单来说,装箱就是自动将基本数据类型转换为包装器类型;拆箱就是自动将包装器类型转换为基本数据类型。

在这里插入图片描述

上图为八种基本数据类型和其对应的包装类。

1.2 装箱和拆箱是如何实现的?

通过代码说明:

首先我们创建一个Main函数,如下:

public class Main {
    public static void main(String[] args) {
        Integer i = 100;        
        int j = i;
    }
}

编译后打开项目所在路径,找到Main.class文件,用IDEA打开,发现经过编译后的代码如下:

public class Main {
    public Main() {
    }

    public static void main(String[] var0) {
        Integer var1 = Integer.valueOf(100);
        int var2 = var1.intValue();
    } }

可以很清楚的见到程序运行时拆箱和装箱的过程,而且能看到该过程是通过基本数据类型的valueOf()方法去实现的。

1.3分析下源码:

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

//再来看下IntegerCache的源码

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) {
                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);
            }
            high = h;
  cache = new Integer[(high - low) + 1];
            int j = low;
            for(int k = 0; k < cache.length; k++)
                cache[k] = new Integer(j++);
        }
   private IntegerCache() {}
    }

通过分析Integer的源码我们既可以明白最上边的那个问题为啥是true和false了。
源码给定的范围是-128~127,也就是说在这个范围内的话,直接取,不必再创建对象了,所以上面的两个变量自然指向同一地址,最后结果返回true,而若是超过范围,则需要装箱,也就是创建一个新的对象,那么两个变量就各自分配到了一个新的地址,结果自然为true。
其中应该还涉及到一部分常量池的内容,等抽空儿再详细的写一下。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值