Java中的装箱和拆箱

本文详细解释了Java中装箱和拆箱的概念及其实现原理,并通过实例代码展示了这一过程中的常见误区。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

**最近遇到了有关java中装箱和拆箱的问题,今天认真参考各位大佬文章和阅读源码后将一点理解记录下来。**

一.什么是装箱?什么是拆箱?

装箱:将基本类型⽤它们对应的引⽤类型包装起来;
拆箱:将包装类型转换为基本数据类型;

在Java SE5之前,如果要生成一个数值为5的Integer对象,必须这样进行:
Integer i = new Integer(5);

从Java SE5开始就提供了自动装箱的特性,如果要生成一个数值为5的Integer对象,只需要这样就可以了:

Integer i = 5;

这个过程中会自动根据数值创建对应的 Integer对象,这就是装箱。

那什么是拆箱呢?顾名思义,跟装箱对应,就是自动将包装器类型转换为基本数据类型:

Integer i = 5;  //装箱
int n = i;   //拆箱

总而言之,装箱就是将基本数据类型转换为包装器类型;拆箱就是 自动将包装器类型转换为基本数据类型。

基本数据类型对应的包装器类型:

基本类型包装类型
int(4字节)Integer
byte(1字节)Byte
short(2字节)Short
long(8字节 )Long
float(4字节)Float
double(8字节)Double
char(2字节)Character
boolean(未定)Boolean

二.装箱和拆箱是如何实现的?

装箱过程是通过调用包装器的valueOf方法实现的,而拆箱过程是通过调用包装器的 xxxValue方法实现的。
装箱:

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

拆箱:

@HotSpotIntrinsicCandidate
    public int intValue() {
        return value;
    }

三.误区

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

猜测的结果:true,true或者false false
但是事实上输出结果是:

true
false

源码:

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 =
                VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
            if (integerCacheHighPropValue != null) {
                try {
                    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);
                } catch( NumberFormatException nfe) {
                    // If the property cannot be parsed into an int, ignore it.
                }
            }
            high = h;

            cache = new Integer[(high - low) + 1];
            int j = low;
            for(int k = 0; k < cache.length; k++)
                cache[k] = new Integer(j++);

            // range [-128, 127] must be interned (JLS7 5.1.7)
            assert IntegerCache.high >= 127;
        }

        private IntegerCache() {}
    }


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

所以,原因显而易见!

注意:当包装类型为double时,结果不同。上源码:

@HotSpotIntrinsicCandidate
    public static Double valueOf(double d) {
        return new Double(d);
    }

若有错误之处,欢迎补充!

https://www.cnblogs.com/dolphin0520/p/3780005.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值