从源码分析128陷阱

目录

128陷阱

问题产生的原因

通过Integer源码分析

总结


128陷阱

当比较使用Integer声明的两个个变量的范围在[-128,127]时,使用“==“与”equals“的结果都为true,但是当数据超出这个范围时,使用”==“为false而使用”equals“为true

package explore;

public class test0830 {
    public static void main(String[] args) {
        Integer a = 10;
        Integer b = 10;
        Integer c = 1000;
        Integer d = 1000;

        System.out.println("a==b :" + (a==b));
        System.out.println("c==d :" + (c==d));
        System.out.println("a.equals(b) :" + (a.equals(b)));
        System.out.println("c.equals(d) :" + (c.equals(d)));
    }
}

问题产生的原因

一般来说,”==“是比较的是内存的地址,而“equals”比较的是内容。

使用”==“进行比较的时候,在[-128,127]区间内,系统会从缓存中读取数据,指向的是同一地址,而超出这个范围地址就会new新的Integer对象,即使值相同的两个数地址也不同了。

通过Integer源码分析

首先,Integer是int的包装类,声明一个变量实际上是new一个Integer对象,对int进行自动包装,包装使用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和IntegerCache.high之间时,valueOf()方法会调用下面的方法

    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) {
                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() {}
    }
  1. low最小值为Integer内部定义的-128,而high最大值内部默认从VM中读取预设的数据,最大值为127,也可以通过属性配置最大值,但是要大于127,否则最大值还是127
  2. 然后将用于缓存的数组cache大小设为high+(-low),将这些数全部存于缓存
  3. 最后通过assert断言最大值是否不小于127,true则系统正常执行,false则抛出系统级错误 

总结

通过对Integer源码的分析,发现在声明变量时Integer内部会自动包装int,当value在[-128,127]区间时,内部会调用IntegerCache()方法,该方法会将这256个数存入缓存,当再声明一个这区间的数的时候,就从缓存中获取地址,这些数最终指向的都是同一个地址。但是当声明一个这个区间外的数时,每次都是new一个新的对象,即使数相同也会开辟新地址。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值