在Java中有比简单的if-else更好的方法来否定布尔值吗?

if (theBoolean) {
    theBoolean = false;
} else {
    theBoolean = true;
}

当前回答

类BooleanUtils支持布尔值的否定。您可以在commons-lang:commons-lang中找到这个类

BooleanUtils.negate(theBoolean)

其他回答

theBoolean = !theBoolean;
Boolean original = null; // = Boolean.FALSE; // = Boolean.TRUE;
Boolean inverse = original == null ? null : !original;
theBoolean ^= true;

如果变量长度超过4个字母,则按键次数更少

编辑:代码在用作谷歌搜索词时往往会返回有用的结果。上面的代码没有。对于那些需要它的人,它是按位异或,如下所述。

之前:

boolean result = isresult();
if (result) {
    result = false;
} else {
    result = true;
}

后:

boolean result = isresult();
result ^= true;

类BooleanUtils支持布尔值的否定。您可以在commons-lang:commons-lang中找到这个类

BooleanUtils.negate(theBoolean)