从源码分析128陷阱

本文深入解析了Java中基本数据类型与包装类型的装箱和拆箱过程,特别是Integer对象的缓存机制。当数值在-128到127之间时,Integer对象会复用已存在的实例,否则每次都会创建新的对象。因此,当使用‘==’比较超出此范围的Integer对象时,即使数值相同,由于对象地址不同,结果也会为false。通过对源码的分析,我们可以更好地理解这一行为。

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

装箱

将基本数据类型转化为包装类型。

两种方式

Integer i = new Integer(1);

Integer i = Integer.valueOf(1);

拆箱:

将包装类型转换为基本数据类型

int value = i.intValue();

 

源码

    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;
            //可以通过JVM参数java.lang.Integer.IntegerCache.high来设置缓存的最大值
            String integerCacheHighPropValue =
                sun.misc.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后的的布尔表达式永真才不报错,即保证high最小也得是127,要不然我就抛异常
            assert IntegerCache.high >= 127;
        }
 
        private IntegerCache() {}
    }
    public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

由以上代码不难看出:
 当 i >= IntegerCache.low && i <= IntegerCache.high时,返回一个已经存在于指定数组中的对象,而当其超出范围的时候,则新建一个对象。
而Java中两个用==比较对象时,比较的是它的地址。所以当i超出范围时,用双等号比较两对象,实际上是比较两个具有相同值的不同地址的对象,结果为false。

  我们对一段代码进行测试

结果为

 

前两行

128陷阱只针对与Integer和Integer之间,当一个int和Integer作“==”运算的时候,Integer会自动拆箱,即作数值是否相等的运算,即前两行都为true。

第三行

 当 i >= IntegerCache.low && i <= IntegerCache.high时,返回一个已经存在于指定数组中的对象,而当其超出范围的时候,则新建一个对象,即128超出范围,此时默认创建了两个地址不同的对象。
而Java中两个用==比较对象时,比较的是它的地址。所以当i超出范围时,用双等号比较两对象,实际上是比较两个具有相同值的不同地址的对象,结果为false。

第四行

通过对源码的分析,当 i >= IntegerCache.low && i <= IntegerCache.high时,返回的是一个数组中的同一个对象,所以当进项==判断时,结果为true。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值