7
if (first != null && second != null && !first.equals(second)) {
  // not null & not equal
} else if (first == null ^ second == null) {
  // not both null and not both not null
  // (first == null && second != null) || (first != null && second == null)
} else {
  // both null or equal
}

FindBugs 抱怨 else if (first == null ^ second == null) {...}

4

5 回答 5

0

既然您在评论中写道:not both nullFindBugs 向您展示了您的(潜在)错误是一件好事,因为您应该使用&&(AND)而不是^(XOR):

first != null && second != null

或者:

!(first == null || second == null)

更新:
OP 将注释更改为:“既不是空的,也不是都不是空的”这种情况需要不同的if

(first == null && second != null) || (first != null && second == null)

这相当于:

first == null ^ second == null

只是以前的版本更具可读性。

于 2013-10-15T21:06:05.267 回答
0

可能是因为它只是软件。

于 2013-10-15T21:02:53.477 回答
0

警告说:冗余空检查。因此,FindBugs 认为您正在冗余地检查变量的无效性。试试这个代码是否也触发了警告:

    Boolean firstNull = (first == null);
    Boolean secondNull = (second == null);
    Boolean equalFirstSecond = first.equals(second);

    if (!firstNull && !secondNull && !equalFirstSecond) {
        // not null & not equal
    } else if (firstNull ^ secondNull){
        // not both null and not both not null
    } else {
        // both null or equal
    }
于 2014-05-05T08:28:46.050 回答
0

^ 运算符是位运算符,而不是逻辑运算符。虽然在技术上是正确的,但如果逻辑表达式增长,运算符的优先级会使表达式变得混乱。我不使用 FindBugs,但我会称第 3 行为可疑 - 将其包裹在括号中或重写它。

 ...
 } else if ((first == null) ^ (second == null)) {
 ...

只要操作数是布尔值,^ 就可以像逻辑运算一样表现。由于每个逻辑运算符和位运算符的优先级不同,因此您应该始终使用括号进行分组,因为评估顺序不会从左到右,而是基于此处的表格:http: //docs.oracle.com/javase/教程/java/nutsandbolts/operators.html

你的表达式“not both null”和“not both not null”如下所示:

(first == null) || second == null) && !((first == null && second == null))

这很令人困惑,但这是您所要求的。

我不确定你在块中做什么,但像这样编写整个块可能更容易:

if(first!=null && !first.equals(second)) {
  // first is not null and the first and second are not equal
} else if (second!=null && !second.equals(first)) {
  // second is not null and first and second are not equal
} else {
  // all that is left is that first and second are both null OR neither one is null but they are equal
}
于 2013-10-15T21:22:58.087 回答
-2

if (first != null && second != null && !first.equals(second)) {

你不需要在second != null这里测试。equals()通话就是这样做的。

} else if (first == null ^ second == null) {

在这种情况下,您应该返回false,假设这是一个equals()方法本身。

如果 FindBugs 不喜欢这个更改,我会忽略它,它不知道它在说什么。这并不完美。放入例外规则。

于 2013-10-16T07:22:18.620 回答