深刻理解Integer包装类型

先看一个demo:

public class Test {

    public static void main(String[] args) {

        Integer a = 128;
        Integer b = 128;
        Integer c = 127;
        Integer d = 127;
        int e = 200;
        int f = 200;
        System.out.println(a == b);
        System.out.println(c == d);
        System.out.println(a.intValue() == b.intValue());
        System.out.println(e == f);
        System.out.println(a.equals(b));
        System.out.println(c.equals(d));

        System.out.println("=============我是分割线==============");

        Integer aa = -129;
        Integer bb = -129;
        Integer cc = -128;
        Integer dd = -128;
        int ee = -200;
        int ff = -200;
        System.out.println(aa == bb);
        System.out.println(cc == dd);
        System.out.println(aa.intValue() == bb.intValue());
        System.out.println(ee == ff);
        System.out.println(aa.equals(bb));
        System.out.println(cc.equals(dd));

    }

}

运行结果如下:

false
true
true
true
true
true
=============我是分割线==============
false
true
true
true
true
true

那么问题来了,大家都知道 == 比较的是两个对象的引用,为什么 两个包装类型的Integer:127对象是同一个引用,而两个包装类型的Integer:128对象,就是两个不同的对象了呢?

这是因为每次通过自动装箱得到一个Integer对象,先通过判断是否IntegerCache.cache 缓存数组的范围之内,如果在直接从缓存数组中取,如果不在,就重新new。

而默认的缓存范围是:[-128,  127]

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

可以通过设置VM 参数,改变这个缓存数组的范围: -XX:AutoBoxCacheMax=

所以包装类型的比较,最好不要直接比较,转换成其对应的基本类型进行比较,可防止出现bug

我们尝试修改一下VM启动参数,

修改VM参数后,重新运行上述代码,结果变成了:

true
true
true
true
true
true
=============我是分割线==============
false
true
true
true
true
true

我们发现,两个装箱的Integer:128也指向cache数组的同一个引用了。

注意: 根据需要,可以通过VM参数扩充Integer 缓存数组的缓存范围。IntegerCache 只能修改Integer 的缓存上限。

其他的包装类型有些也是有缓存的:

只是除了Integer类型的可以通过VM参数设置缓存范围,其他类型不可设置。

JDK对基础包装类型使用缓存,对于大型项目,大量使用基础数据类型的来说,肯定是节省了部分的空间,这也是一种优化吧。

 

最后,给大家分享一道面试题:

        Integer a = new Integer(11);
        Integer b = new Integer(11);
        Integer c = 11;
        Integer e = 11;
        int d = 11;
        
     
        System.out.println(a == b);
        System.out.println(a == c);
        System.out.println(a == d);
        System.out.println(c == d);
        System.out.println(c == e);

运行结果:

false
false
true
true
true

至于原因,我简单说下,两个不同的 new Integer(),肯定不同,cache数组中,只是提前帮我们 new 好了,[-128, 127]的对象,并且只有自动装箱的时候,才会引用到这个数组内的对象!

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值