在Java中有比简单的if-else更好的方法来否定布尔值吗?
if (theBoolean) {
theBoolean = false;
} else {
theBoolean = true;
}
在Java中有比简单的if-else更好的方法来否定布尔值吗?
if (theBoolean) {
theBoolean = false;
} else {
theBoolean = true;
}
当前回答
theBoolean ^= true;
如果变量长度超过4个字母,则按键次数更少
编辑:代码在用作谷歌搜索词时往往会返回有用的结果。上面的代码没有。对于那些需要它的人,它是按位异或,如下所述。
其他回答
这个答案出现在搜索“java反转布尔函数”时。下面的示例将防止某些静态分析工具由于分支逻辑而导致构建失败。这是有用的,如果你需要反转一个布尔值,还没有建立全面的单元测试;)
Boolean.valueOf(aBool).equals(false)
或者:
Boolean.FALSE.equals(aBool)
or
Boolean.FALSE::equals
之前:
boolean result = isresult();
if (result) {
result = false;
} else {
result = true;
}
后:
boolean result = isresult();
result ^= true;
类BooleanUtils支持布尔值的否定。您可以在commons-lang:commons-lang中找到这个类
BooleanUtils.negate(theBoolean)
theBoolean ^= true;
如果变量长度超过4个字母,则按键次数更少
编辑:代码在用作谷歌搜索词时往往会返回有用的结果。上面的代码没有。对于那些需要它的人,它是按位异或,如下所述。
theBoolean = !theBoolean;