【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。

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