为什么不要使用==比较Integer?

比较Integer的时候,不要用==。
查看Integer的源码,如下:

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

通过注释可以知道,为了更好的空间和时间性能,Integer会缓存频繁使用的数值,数值范围为-128到127,在此范围内直接返回缓存值。
IntegerCache.low 是-128,IntegerCache.high是127,如果在这个区间内,他就会把变量i当做一个变量,放到内存中;
但如果不在这个范围内,就会去new一个Integer对象,
而如果两个Integer值都不在这个范围内,那么就会new了两个对象实例,两个对象用==比较肯定是false。

解决方法

比较Integer的值有两种方法,
1.一个是用equals()比较,但是注意要判空,避免空指针异常。
2.一个是用intValue()转成int比较。
示例如下:

        Integer value1=129;
        Integer value2=129;
        if(value1.intValue()==value2.intValue()){
            // ...
        }

参考资料:
https://blog.csdn.net/luohao_/article/details/86607686

posted on   乐之者v  阅读(1154)  评论(1编辑  收藏  举报

编辑推荐:
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· C++代码改造为UTF-8编码问题的总结
阅读排行:
· 【.NET】调用本地 Deepseek 模型
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
< 2025年2月 >
26 27 28 29 30 31 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 1
2 3 4 5 6 7 8

导航

统计

点击右上角即可分享
微信分享提示