Integer中equlas()方法的运用与问题总结

说实话,在写这篇博文之前真的不知道Integer还有这么一个大坑。还好最近看了阿里v1.2版本的Java开发手册才发现了,先给自己打个预防针。

1.问题

下面我们先来看几小段代码,先自己想想运行结果是什么?

public class Test1{
    public static void main(String[] args) {
        Integer a=100;
        Integer b=100;
        if(a==b){
            System.out.println("a==b is true");
        }
        if(a.equals(b)){
            System.out.println("a.equals(b) is true");
        }
    }
}

Test1中的运行结果是什么?有点基础的人都应该答对了。

a==b is true
a.equals(b) is true

public class Test2{
    public static void main(String[] args) {
        Integer a=1000;
        Integer b=1000;
        if(a==b){
            System.out.println("a==b is true");
        }
        if(a.equals(b)){
            System.out.println("a.equals(b) is true");
        }
    }
}

Test2中的结果呢?很多人会在想,这有什么区别吗?不就把100变成了1000么,结果还能不一样?
的确,结果不一样。

a.equals(b) is true

Why?Why?Why?世界观快要崩塌。不着急,慢慢来。

2.解密

唯一的不同就是数字不一样,难道数字有什么鬼么?你要注意到的是定义的类型是Integer,这不是一个基本类型,是一个包装类。难道类里面有什么鬼?想想看,Integer包装类我们最常提到的概念是什么?自动拆箱和装箱。了解一点自动拆箱和装箱的同学都知道,它是由intValue()和valueOf()实现的,那么我们看看源码。

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

貌似intValue没什么可看的,那我们来看看valueOf(),这个方法中出现频率最高的类是IntegerCache。我们在Integer中可以发现这个类,它是Integer的静态内部类。

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

引用开发手册中的话来解释一下。

在-128至127范围内的赋值,Integer对象是在IntegerCache.cache产生,会复用已有对象,这个区间内的Integer值可以直接使用==进行判断,但是这个区间之外的所有数据,都会在堆上产生,并不会复用已有对象

扫描二维码关注公众号,回复: 464198 查看本文章

这下子是不是恍然大悟。所以强烈推荐使用equals()方法判断两个包装类值是否相等。
赶紧去试试吧,加深一下印象。不知道这个坑,以后在这上出了BUG真的是不容易发现啊。^_^

参考:

  • 阿里巴巴Java开发手册v1.2.0

猜你喜欢

转载自blog.csdn.net/tb3039450/article/details/72773787
今日推荐