导航
导航

一个有点意思的Java知识点

java一个面试知识点 你应该会遇见过,如下:

Integer a = 100 ;
Integer b = 100 ;
Integer c = 200 ;
Integer d = 200 ;
System.out.println(a==b);
System.out.println(c==d);

有经验的 会想到这个是要考我们关于Integer的缓存机制范围问题

Integer的缓存机制 [-128,127]
所以 a == b 结果为 true , c == d 结果为 false

基本上,问题到这也就完了,因为考的目的已经达到了。
but,,,如果有“较真”的面试官询问 怎么让c==d为true? 因吹斯听,这真是一个有意思的question

看了jdk源码 有关Integer的


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

[-128,127]的出处。

通过设置 -XX:AutoBoxCacheMax 属性 设置jvm最大的Integer缓存池范围
这样

完工。。。。

过来补个知识,其他包装类的缓存机制范围

Boolean:(全部缓存)
Byte:(全部缓存)
Character(<= 127缓存)
Short(-128 — 127缓存)
Long(-128 — 127缓存)
Float(没有缓存)
Doulbe(没有缓存)