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对象即可,在范围外的才需要重新实例化。

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