^ 运算符是位运算符,而不是逻辑运算符。虽然在技术上是正确的,但如果逻辑表达式增长,运算符的优先级会使表达式变得混乱。我不使用 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
}