Java Integer类源码<三> valueOf()方法

valueOf方法

static Integer valueOf(int i)
返回一个 Integer指定的 int值的 Integer实例。
static Integer valueOf(String s)
返回一个 Integer对象,保存指定的值为 String 。
static Integer valueOf(String s, int radix)
返回一个 Integer对象,保存从指定的String中 String的值,当用第二个参数给出的基数进行解析时。

我们看到代码其实是调用的parseInt()方法
关于parseInt方法解析请看
Java Integer类源码<二> parseInt()方法
今天我们主要分析IntegerCache这个内部类

   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));
    }
    private static class IntegerCache {
        static final int low = -128;
        static final int high;
        static final Integer cache[];

        static {
            //默认最大值
            int h = 127;
            //我们也可以通过修改JVM设置来修改这个默认范围的最大值
            String integerCacheHighPropValue =
                sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
            if (integerCacheHighPropValue != null) {
                try {
                    //将字符串转换成整型
                    int i = parseInt(integerCacheHighPropValue);
                    //取较大值
                    i = Math.max(i, 127);
                    //限定了cache数组大小最大为为Integer.MAX_值
                    h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
                } catch( NumberFormatException nfe) {
                    
                }
            }
            high = h;
            //指定数组cache的大小
            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() {}
    }

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
文章参照转载:
https://blog.csdn.net/lianjiww/article/details/91643762
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。