關於Integer自動拆包

Integer i = 1;

Integer j = 1;

i==j 猜一猜這個答案是什麼?

大夥肯定認爲是true吧,也沒錯,那當i和j爲下面的值時

Integer i = 129;

Integer j = 129;

i==j 大家再猜一猜這個答案是什麼?

輸出爲false;

具體原因是

public static Integer valueOf(String s) throws NumberFormatException {
        return Integer.valueOf(parseInt(s, 10));
    }

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


都是返回IntegerCache 這個值

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用ValueOf出來的都是同一個對象。

解決方案:

可用Integer .intValue();來比較值;

或者調用 i.equals(j)

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