Integer类小细节随笔记录

  先看一段简单的代码:

       Integer v1 = Integer.valueOf(12);
       Integer v2 = Integer.valueOf(12);

       Integer v3 = Integer.valueOf(129);
       Integer v4 = Integer.valueOf(129);

       System.out.println(v1 == v2);
       System.out.println(v3 == v4); 

  输出结果是啥呢?第一个是 true,第二个是false。

  为啥呢?

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

  看源代码得知,当 在默认条件下(-127到128)之间,从缓存中取值,否则重新 new 一个 Integer 对象。详细代码如下:

 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;
        }

  所以,我们上述的代码运行结果为 true 和 false。Integer(12) 两次都是取的缓存的值,129两次分别重新创建对象。

  不过从注释上可以了解到,可以调整jvm参数来定缓存数组的大小。

* The cache is initialized on first usage.  The size of the cache
     * may be controlled by the {@code -XX:AutoBoxCacheMax=<size>} option.

  

 

  再次重新运行,输出结果都为 true。因为把缓存集合的空间大小调整到了 130 + 127 ,所以 129 也从缓存中取。再试一次 取131 对比。

  

 

posted @ 2018-03-12 15:02  丶Pz  阅读(145)  评论(0编辑  收藏  举报