【Java】Integer类型比较

   public static void main(String[] args) {
        Integer x = 128, y = 128;
        System.out.println(x == y);   false
        Integer s = 127, t = 127;
        System.out.println(s == t);   true
    }

先说结论

Integer的比较在【-128,127】之间的数时,俩对象“==”返回true

不在这一范围的返回false。

 

具体原因看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() {}
    }

在integer中有个静态内部类定义了缓存池,范围是-128到127之间,在类加载的期间就已经完成,需要的时候直接指向,省去了构造对象的时间,提高了效率。

实际上Integer s = 127, t = 127;中s和t指向的是同一对象,“==”比较对象的地址是否相等,故打印出true。

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

上述代码可以看出当int i自动装箱的时候判断了i的范围是否在-128到127之间,如果是则直接返回缓存的对象,

如果不是则new了一个新对象。

所以Integer x = 128, y = 128;实际上是x和y分别new了Integer对象,分别指向了不同对象的地址,故打印出false。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章