Integer比较相等的问题

 Integer类型匹配项等的时候一定要用 equals() 方法!不要用 == 

这绝对是个大坑!

 

记得是有一次查询数据,数据封装到实体类进行数据匹配的时候,出现了Integer类型比较像等的问题,明明两个数是一样的,但是就是匹配不上。

一个很简陋的例子:

public static void main(String[] args) {

    Integer a = 333;
    Integer b = 333;

    if (a == b){
        System.out.println(true);
    } else {
        System.out.println(false);
    }
}

结果输出:

 

明明是一样的数,结果没有匹配成功;

 

虽然Integer不用创建对象就能赋值数据,但是它始终是一个包装类

点进Integer的源码里面就能看到

    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() {}
    }
    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之间的值的时候,Integer直接把这些值放进常量池里面,这个时候,用 == 是可以比较的。

比如:

    public static void main(String[] args) {

        Integer a = -128;
        Integer b = -128;

        if (a == b){
            System.out.println(true);
        } else {
            System.out.println(false);
        }
    }

结果输出:

 

但是当赋给Integer值超过这个范围的时候,Integer就会创建对象,值就不放在常量池里面了,这个时候再用 == 就不可以比较了,因为存放的位置都不一样了,数一样还是会返回false

 

所以Integer的话强烈建议用 equals() 这个方法!

    public static void main(String[] args) {

        Integer a = 2345;
        Integer b = 2345;

        if (a.equals(b)){
            System.out.println(true);
        } else {
            System.out.println(false);
        }
    }

结果:

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

你过来啊~

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

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

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

打赏作者

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

抵扣说明:

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

余额充值