Integer常量緩存池(二)

什麼是Integer常量緩存池

當我們使用Integer的時候會存儲數據,避免重複的new對象,緩存數據的範圍在-128 到127 之間的數據, 如果超出這個數據則創建一個新的對象

爲什麼會有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);
                    // 表示最大值在127
                    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;
            // 把數據緩存在cache數組中
            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 的valueof 方法

//判斷數據是否在這個之間,如果在則返回緩存中的數據
    public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

利用equal比較爲什麼爲false

        Integer s1= 100;
        Integer s2= 100;
        System.out.println(s1==s2);
        //打印
        true
        
        Integer s1= 128;
        Integer s2= 128;
        System.out.println(s1==s2);
        //打印
        false

爲什麼出現這個原因?
是因爲我們的直接量超出了integer的緩存範圍所以出現了兩個對象.

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