integer == integer返回 true 还是 false?

看到了一个比较坑的问题:integer == integer 返回 true 还是 false 呢?
所以你觉得下面两个输出是什么呢?(波浪线忽略,是因为封装类型不建议用“==”,应该是equals)
在这里插入图片描述
在这里插入图片描述
答案很简单,第一个 integer = 20, 返回的是 true,第二个 integer = 321 返回的是false !!!
what???
是因为,
一来:Integer里弄了一个缓存,对于在 -128—127 之间的数值,会直接使用该缓存里的对象 ;
所以也就是说 在我们比较 integer = 20 的时候,其实拿取的是同一个对象,所以会返回true。
二来:因为321超出了 -128~127这个区间,那么系统会重新生成新的对象,所以比较的时候就会拿取不同的对象做比较,因此就会返回false。

为甚呢?
对于Integer类java为了提高效率(integer在加载时就会调用Integer.valueOf()方法),初始化了-128–127之间的整数对象,因此Integer类取值-128–127的时候效率最高。

部分源码如下:

tatic {
        // 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;
    }

当然integer和int的取值范围还是一致的
取值范围是从-2147483648 至 2147483647(-231至 231-1) ,包括-2147483648 和 2147483647。

  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Java程序源

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值