Integer相等问题,源码分析,一看就懂

Integer相等问题
先上代码说结论,-128到127之间的两个Integer用==比较是相等的。之外的不等。

		Integer n1 = 1;
        Integer n2 = Integer.valueOf(1);
        System.out.println(n1.equals(n2));//true
        System.out.println(n1 == n2);//true
        
        Integer m1 = Integer.valueOf(128);
        Integer m2 = Integer.valueOf(128);
        System.out.println(m1.equals(m2));//true
        System.out.println(m1 == m2);//false

为什么?
首先我们要知道== 和equals的区别,==比较的是地址,equals比较的是内容。
比如

 		Integer a=new Integer(125);
        Integer b=new Integer(125);
        System.out.println(a==b);//fasle
        System.out.println(a.equals(b));//true

肯定不相等,因为new出来的在堆空间,==就不相等呗。
其次,我们要知道

Integer n1 = 1;

等价于

 Integer n1 = Integer.valueOf(1);

这又是为什么,我们可以跟进到源码里面看一下,idea默认是不能进入源码的,要跟进到源码需要设置一下idea,没设置看这篇文章。
https://blog.csdn.net/changbaishannefu/article/details/119039695

现在我们就可以从源码级别来分析了。
下面是一个内部类和valueof方法的方法。大家可以清楚额看到当在-128-127时候没有new新对象,而是对应于内部类的的cache数组的值,所以当声明两个integer的时候,他们对应的是同一个,故相等。当不在范围内时,是new的对象,所以不相等。

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() {}
    }

 public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值