美文网首页
Integer类的自动装箱

Integer类的自动装箱

作者: CarsonCao | 来源:发表于2019-11-12 20:34 被阅读0次
           Integer a = 1;
           Integer b = 1;
           Integer c = 200;
           Integer d = 200;
    
           System.out.println(a == b);
           System.out.println(c == d);
    
    true
    false
    

    为什么表面看起来一样的数据,结果却不同?原因是java编译器在Integer装箱操作时,做了一些特殊的处理。我们来详细看下。

    自动装箱时编译器调用valueOf将原始类型值转换成对象:

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

    我们看得到在装箱过程中,首先判断IntegerCache中是否缓存了数据,如果缓存了直接从缓存中取,超过缓存范围会直接new 一个新的Integer对象。那么上面我们的c==d输出为false,应该是200 超过了IntegerCache缓存的范围,我们看下IntegerCache的源码:

    /**    
     * Cache to support the object identity semantics of autoboxing for values between
         * -128 and 127 (inclusive) as required by JLS.
         *
         * The cache is initialized on first usage.  The size of the cache
         * may be controlled by the {@code -XX:AutoBoxCacheMax=<size>} option.
         * During VM initialization, java.lang.Integer.IntegerCache.high property
         * may be set and saved in the private system properties in the
         * sun.misc.VM class.
         */
    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]的Integer对象。
    我们可以通过设置JVM启动参数-Djava.lang.Integer.IntegerCache.high=200来间接设置IntegerCache.high的值,也可用-XX:AutoBoxCacheMax设置。

    除了Integer类有缓存之外,Boolean,Byte,Short,Long都存在缓存:

    • Boolean的true和false都会缓存在内存中,自己new的是另一个空间;
    • Byte的256个值全部缓存在内存中,自己new的是另外的空间;
    • Short、Long两个的cache范围为定死的[-128, 127],不想Integer一样能动态设置。
    • Float、Double没有cache。

    相关文章

      网友评论

          本文标题:Integer类的自动装箱

          本文链接:https://www.haomeiwen.com/subject/wqcjbctx.html