java int -128到127问题

最近发现一个有趣的事情,发现使用java的自动装箱方式设置Integer i1=66,i2=66时,i1和i2竟然是一个对象,

public static void main(String... args){
        Integer i1 = 128;
        Integer i2 = 128;
        /*
             由于自动装箱是编译器阶段,所以以上代码会在编译器变成
             Integer i1 = new Integer(128);
             Integer i2 = new Integer(128);
             由于i1和i2指向堆中创建的两个对象所以 i1==i2会输出false
        */
        System.out.println(i1 == i2); // false

        Integer i3 = 127;
        Integer i4 = 127;
        System.out.println(i3 == i4); // true
        /*
        结果却输出了true,这是由于java.lang.Interger中做了缓存,其默认范围是-128~127,
        所以如果Integer指向这个范围内的数字在编译的时候会直接定位到该缓存中的数字,而不会创
        建新的对象,所以输出为true。
        */
    }

查阅后得知,java.lang.Integer(since 1.5)中做了缓存:

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

    /**
     * Returns an {@code Integer} instance representing the specified
     * {@code int} value.  If a new {@code Integer} instance is not
     * required, this method should generally be used in preference to
     * the constructor {@link #Integer(int)}, as this method is likely
     * to yield significantly better space and time performance by
     * caching frequently requested values.
     *
     * This method will always cache values in the range -128 to 127,
     * inclusive, and may cache other values outside of this range.
     *
     * @param  i an {@code int} value.
     * @return an {@code Integer} instance representing {@code i}.
     * @since  1.5
     */
    public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

默认缓存-128-127,可以通过java.lang.Integer.IntegerCache.high进行设置。

但是,该方式仅对自动装箱有效,若是走正常的new,仍是各自生成新的实例!!

(不要像某些文章说的是什么常量池里,以后获取就都是,放在常量池不假,但是具体的获取是由Integer决定的,仅在自动装箱时会读取缓存)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值