JDK源碼解讀(第八彈:Integer之valueOf方法)

Integer的valueOf方法也是比較常用的方法,總共有 3個valueOf方法。不過看這幾個方法之前,需要先了解一下內部類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() {}
    }

IntegerCache是Integer的一個內部類,默認情況下,它緩存了-128到127的256個Integer實例。
當Integer的值範圍在這個範圍內時則直接從緩存中獲取對應的Integer對象,不會重新實例化。
這些緩存的實例都是靜態且final的,避免重複的實例化和回收。
所以如果我們獲取兩次緩存範圍內的同一個Integer的話,他們將會是完全相等的,不僅僅是值相等,因爲他們引用的是同一塊內存上的對象。
比如下面的代碼,雖然值都是相等的,都是127,但是a1和a2是不等的,而b1和b2是相等的:

Integer a1 = new Integer(127);
Integer a2 = new Integer(127);
Integer b1 = Integer.valueOf(127);
Integer b2 = Integer.valueOf(127);
System.out.println(a1 == a2);  // false
System.out.println(b1 == b2); // true

我們也可以通過修改JVM設置來修改這個默認範圍的最大值,但是不能小於127。

然後就來看一下valueOf方法:

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

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

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

後面兩個方法都是調用第一個方法,所以主要看一看第一個方法。
可以看到,valueOf方法其實就是根據傳入的參數調用構造函數構造一個Integer對象的實例來返回。
因爲有IntegerCache緩存,所以在範圍內的直接從IntegerCache的cach數組中獲取現成的Integer對象即可,在範圍外的才需要重新實例化。

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