为什么不要使用==比较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()){
            // ...
        }

参考资料:Integer判断==遇到的坑_程序猿-Allen的博客-CSDN博客

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值