编程语言
首页 > 编程语言> > java – FindBugs:双引用的可疑比较

java – FindBugs:双引用的可疑比较

作者:互联网

我有一个方法,需要两个双打a和b(注意大写’D’)并计算差异.如果只有一个参数为空,则结果应为999999,否则将返回两个数字之间的差值.

以下(工作)代码在FindBugs中给出了一个“可怕的”警告,我通常会尝试避免代码中的高级别警告.但是,我认为代码既简短又易读,而我能想到的其他一切只会降低其可读性.在这种情况下,使用==的恕我直言是完全正确的.

public double foo(Double a, Double b) {
    return a == b ? 0 : (a != null && b != null) ? b - a : 999999;
}

FindBugs报告该行:

Bug: Suspicious comparison of Double references in
Main.foo(Double, Double)

This method compares two reference values using the == or != operator,
where the correct way to compare instances of this type is generally
with the equals() method. It is possible to create distinct instances
that are equal but do not compare as == since they are different
objects. Examples of classes which should generally not be compared by
reference are java.lang.Integer, java.lang.Float, etc.

Confidence: High, Rank: Scariest (1) Pattern: RC_REF_COMPARISON Type:
RC, Category: CORRECTNESS (Correctness)

知道如何在没有警告的情况下重写这段代码干净简单吗?

解决方法:

从长远来看,我建议采取更多步骤来做同样的维护

public double foo(Double a, Double b) {

    //as per Marco suggestion. but not sure OP wants the same.
    if(a == null && b == null){
          return 0;
    } 
    //END
    if(a == null || b == null){
          return 999999;
    }    
    return b-a;  //will return 0 if they are equal. no extra checks required
}

标签:reference-type,java,double,boxing,findbugs
来源: https://codeday.me/bug/20190725/1531085.html