Java判断Integer相等-应该这么这样用

先看下这段代码,然后猜下结果:

Integer i1 = 50
Integer i2 = 50
Integer i3 = 128
Integer i4 = 128
System.out.println(i1 == i2)
System.out.println(i3 == i4)

针对以上结果,估计不少Java小伙伴会算错!

如果在项目中使用==对Integer进行比较,很容易掉坑。

为什么发生以上结果?

1、执行Integer i1 = 50的时候,底层会进行自动装箱:

Integer i1 = 50
//底层自动装箱
Integer i = Integer.valueOf(50)

2、再看==操作

==是判断两个对象在内存中的地址是否相等。所以System.out.println(i1 == i2);System.out.println(i3 == i4); 是判断他们在内存中的地址是否相等。

根据猜测应该全是false或者全是true呀,怎么会不同呢?

3、源码底下无秘密

通过翻看jdk源码,你会发现:如果要创建的 Integer 对象的值在 -128 到 127 之间,会从 IntegerCache 类中直接返回,否则才调用 new Integer方法创建。所以只要数值是正的Integer > 127,则会new一个新的对象。 数值 <= 127时会直接从Cache中获取到同一个对象。

public static Integer valueOf(int i) {
    if (i >= IntegerCache.low && i <= IntegerCache.high)
        return IntegerCache.cache[i + (-IntegerCache.low)];
    return new Integer(i);
}

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
            cache[k] = new Integer(j++)

        // range [-128, 127] must be interned (JLS7 5.1.7)
        assert IntegerCache.high >= 127
    }

    private IntegerCache() {}
}

结论

本文简单分析了下Integer类型的==比较,解释了为啥结果不一致,所以今后碰到Integer比较的时候,建议使用equals

同理,Byte、Shot、Long等,也有Cache,各位记得翻看源码!

本篇完结!感谢你的阅读,欢迎点赞 关注 收藏 私信!!!

原文链接: www.mangod.top/articles/20…[1]、mp.weixin.qq.com/s/7zEKsV51t…[2]

参考资料

[1]

http://www.mangod.top/articles/2023/03/15/1678873359924.html: https://link.juejin.cn/?target=http%3A%2F%2Fwww.mangod.top%2Farticles%2F2023%2F03%2F15%2F1678873359924.html

[2]

https://mp.weixin.qq.com/s/7zEKsV51tdEzkfMGoyLh8Q: https://link.juejin.cn/?target=https%3A%2F%2Fmp.weixin.qq.com%2Fs%2F7zEKsV51tdEzkfMGoyLh8Q

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

技术小羊

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

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

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

打赏作者

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

抵扣说明:

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

余额充值