Integer a=200,Integer b=200,为啥输出是true

654 阅读1分钟

看下自动装箱的代码,用到了 IntegerCache

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

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() {}
    }

通过看源码,我们可以知道 -128 到 127 之间的数会从 IntegerCache 中取出来,超过这个范围,就会 new 出来了一个 Integer 对象。

那没错呀,a 和 b 都是大于127,== 是通过地址值的比较,输出应该是 false。

不知道大家有没有看到这段代码,java.lang.Integer.IntegerCache.high 这个属性可以改变 IntegerCache 的最大值

String integerCacheHighPropValue =
                sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");

加上 -XX:AutoBoxCacheMax=200 这个配置就可以改成 IntegerCache 最大值。

image.png