Integer的valueOf方法源碼閱讀

在網上看到這樣一道題:

System.out.println(Integer.valueOf(127)==Integer.valueOf(127));
System.out.println(Integer.valueOf(128)==Integer.valueOf(128));

輸出結果爲ture和false。爲了弄明白爲什麼會這樣,我們看一下源碼是怎麼實現的。

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) {
                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);
            }
            high = h;

            cache = new Integer[(high - low) + 1];
            int j = low;
            for(int k = 0; k < cache.length; k++)
                cache[k] = new Integer(j++);
        }

        private IntegerCache() {}
    }

在Integer類中有一個靜態內部類IntegerCache,cache[ ]裏面存放了-128~127的數字。 在 VM 初始化期間, 緩存最大值 high, 可能被保存在 sun.misc.VM class 的私有系統屬性裏。

然後我們看一下valueOf是如何實現的:

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

可以看到調用valueOf時會先去緩存中去取,否則纔會創建新的對象。

所以我們也就知道爲什麼開頭的那道題的結果是true和false了。

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