java - 实现compareObjects()的正确方法是什么

标签 java compare

我的compareObjects方法实现如下

public static int compareObjects(Comparable a, Comparable b){

        if (a == null && b == null){
            return 0;
        } else if (a == null && b != null){
            return -1;
        } else if (a != null && b == null){
            return 1;
        } else {
            return a.compareTo(b);
        }
    }

当我通过 findBugs 运行此命令时,我在 return a.compareTo(b) 行上收到此建议:

There is a branch of statement that, if executed, guarantees that a null value will be dereferenced, which would generate a NullPointerException when the code is executed. Of course, the problem might be that the branch or statement is infeasible and that the null pointer exception can't ever be executed; deciding that is beyond the ability of FindBugs. Due to the fact that this value had been previously tested for nullness, this is a definite possibility.

此时a永远不可能为空。为什么 FindBugs 向我显示此建议?我该如何纠正这个问题?实现compareObjects()的正确方法是什么?

最佳答案

我认为这可能是因为您不需要额外的 && 语句。在第一个 if 语句之后,您已经知道其中一个为 null。

public static int compareObjects(Comparable a, Comparable b){

    if (a == null && b == null){
        return 0;
    } else if (a == null){
        return -1;
    } else if (b == null){
        return 1;
    } else {
        return a.compareTo(b);
    }
}

关于java - 实现compareObjects()的正确方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7245490/

相关文章:

java - Tika 1.14 : getting java. PDFTextStripper 的 lang.NullPointerException

javascript - 函数获取指定字符串中每个字母出现的次数

比较 2 个字段的 MongoDb 查询条件

java - 如何将字符串转换为xml

java - 在没有 Spring MVC 的 portlet 中使用 Spring

pdf - PDF 文件的视觉差异以确定像素完美度

ios - 快速检查一个数组是否包含另一个数组的元素

svn - 乌龟SVN : compare two directories (instead of files or revisions)

java - 获取给定月份每周的开始日期和结束日期

c# - 你如何移植一个开源项目?