我的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/