部分包装类型存在缓存机制, 会在JVM启动时, 缓存一定数量的对象, 有助于节省内存, 提高性能.

缓存区间

类型范围是否修改
Integer-128 到 127true : -XX:AutoBoxCacheMax=size 修改
ByteCache-128 到 127false
ShortCache-128 到 127false
LongCache-128 到 127false
CharacterCache0 到 127false

举例

    Integer a = 100;
    Integer b = 100;
    Integer c = 1000;
    Integer d = 1000;
    Integer e = new Integer(100);
    Integer f = Integer.valueOf(100);

    System.out.println(a == b); // true
    System.out.println(c == d); // false
    System.out.println(a == e); // false
    System.out.println(f == e); // false
    System.out.println(a == f); // true

分析

== 在比较对象时, 判断是否指向同一地址

a b f 都是从缓存中取出数据, 所以地址是相同的

c d 不在缓存范围内, 所以是新的对象

e 是新对象

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

可以通过设置 java.lang.Integer.IntegerCache.high 来修改缓存的值. 方法为修改 JVM 的启动参数 -XX:AutoBoxCacheMax=size