java Integer值比较

所有相同类型的包装类对象之间的值比较,应该使用equals方法比较。

–来自阿里巴巴java开发手册。

先看个简单实例:

    public static void main(String[] args)throws Exception{

        Integer a = -121;
        Integer b = -121;
        Integer c = 345;
        Integer d = 345;
        System.out.println(a.equals(b));
        System.out.println(a == b);
        System.out.println(c.equals(d));
        System.out.println(c == d);
    }

这段代码打印结果为:

true
true
true
false

c和d的值都是345,为什么用==和equals比较结果不一样呢?

我们看下对象信息,注意对象地址:

这里写图片描述

Integer值的比较有个坑:对于Integer var = ?,在-128至127范围内的赋值, Integer 对象是在IntegerCache.cache 产生,会复用已有对象,这个区间内的 Integer 值可以直接使用==进行判断,但是这个区间之外的所有数据,都会在堆上产生,并不会复用已有对象;所以,在上面,我们的c和d两个,虽然值是一样的,但是地址不一样。

这是一个大坑,很多人会在项目中使用==来比较Integer!强烈建议,必须使用equals来比较!

猜你喜欢

转载自blog.csdn.net/weixin_39800144/article/details/81165898