java基础之Integer类

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类型
                    int i = parseInt(integerCacheHighPropValue);
                    // 求出二者之间的最大值
                    i = Math.max(i, 127);
                    // 求出二者之间的最小值
                    h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
                } catch( NumberFormatException nfe) {
                    // If the property cannot be parsed into an int, ignore it.
                }
            }
            // 如果上面输入的integerCacheHighPropValue为空,那么这里的最大值就是h
            // 否则就是127.也就是说最大值可以自己来进行指定
            high = h;
			// 默认的是256,所以长度也是256
            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() {}
    }

从上面可以看出默认Integer[]的范围是的是-128到+127,这个已经由静态代码块初始化做好的事情,一旦加载到了JVM中去了,就会存在于JVM中。这里不知道是整数型常量池还是哪里,目前先记住,回头了解清楚了再回来解释。

看一个重要方法:

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

首先会检查一下,传入进来的值,基本类型的值是否在low~high的范围之间,如果在的话,那么就直接返回在数组中的值;如果超过了对应的值,那么将会在堆中创建出来新对象来进行保存。

除此之外,需要看一下这里的内部类,方便来进行学习。

posted @ 2021-09-05 18:18  写的代码很烂  阅读(269)  评论(0编辑  收藏  举报