ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

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

2019-07-25 08:04:10  阅读:316  来源: 互联网

标签:reference-type java double boxing 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

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有