Java 之 整型比较 及 拆箱装箱 findBugs

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lixin2151408/article/details/78611593

今天在用findbugs 时 检查,发现了Suspicious comparison of Integer references , 即定义了integer后,对两个integer进行比较的时候,直接!= 比较,是一个High confidence 的警告,经过看资料,发现了整型比较方法:


java 拥有多种数据类型,常用的整型有 int ,long, 还有对应的包装类型 Integer 和 Long , 在日常开发中,进行整型比较判断时,用equals 还是 == 呢? 这是个简单却容易被忽略的问题,笔者在开发中,通过sonar 或 findbugs 在项目中经常会扫到同事使用不得当的代码. 或许很多人一看到这个,就会马上想起来使用equals() 方法,但是笔者想说的是,条条大路通罗马,equals 并不一定是最佳的解决发难, 先笔者总结如下:

    int    :java 基本类型,比较应该使用 ==

    long :java 基本类型,比较应该使用 ==

    Integer:  java 包装类型, 推荐使用 a.intValue() == b.intValue(), 或equals()

                a == b,  在 128<= Integer <=127 区间内使用== 正确,但是在此区间之外,就会返回false

                a.intValue() == b.intValue(),  正确, 因为intValue() 方法返回的是 int 基本类型数据

                a.equals(b), 正确, equals 方法实际上调的就是 intValue()方法,然后做的比较

        在 128<= Integer <=127 区间内使用== 正确,但是在此区间之外,就会返回false

    Long:  java 包装类型, 推荐使用 a.longValue() == b.longValue(), 或equals()

                a == b,  在 128<= Integer <=127 区间内使用== 正确,但是在此区间之外,就会返回false

                a.longValue() == b.longValue(),  正确, 因为longValue() 方法返回的是 int 基本类型数据

                a.equals(b), 正确, equals 方法实际上调的就是 intValue()方法,然后做的比较


    综上所述,在遇到Long , Integer 此类包装类型的时候,应该使用intValue() 或者 equals() 方法来进行, 第一种效率更高,但是必须要求两个非空,第二个可以处理空指针问题.所以,按需使用即可.


在最近的findbugs检查中,发现了拆箱装箱的问题:如下:

dictionaryPageResDTO.setPvalue(Func.isEmpty(parentDictionaryDTO.getValue())?0:parentDictionaryDTO.getValue());
在这里,出现了问题:
parentDictionaryDTO.getValue())?0:parentDictionaryDTO.getValue()

因为getValue 是 Integer 对象,而我却设置了 0 作为三元运算符中的一个结果,导致了先判断0,从Integer变为 int,然后又变为getValue 的 Integer; 正确的修改为:

dictionaryPageResDTO.setPvalue(Func.isEmpty(parentDictionaryDTO.getValue())?Integer.valueOf(0):parentDictionaryDTO.getValue());


猜你喜欢

转载自blog.csdn.net/lixin2151408/article/details/78611593