在Java中有比简单的if-else更好的方法来否定布尔值吗?
if (theBoolean) {
theBoolean = false;
} else {
theBoolean = true;
}
在Java中有比简单的if-else更好的方法来否定布尔值吗?
if (theBoolean) {
theBoolean = false;
} else {
theBoolean = true;
}
当前回答
有几个
“显而易见”的方式(对大多数人来说)
theBoolean = !theBoolean;
“最短”的路(大多数时候)
theBoolean ^= true;
“最直观”的方式(最不确定)
theBoolean = theBoolean ? false : true;
额外:在方法调用中切换和使用
theMethod( theBoolean ^= true );
由于赋值操作符总是返回已赋值的值,因此这将通过位操作符切换值,然后返回新赋值以用于方法调用。
其他回答
theBoolean = !theBoolean;
theBoolean ^= true;
如果变量长度超过4个字母,则按键次数更少
编辑:代码在用作谷歌搜索词时往往会返回有用的结果。上面的代码没有。对于那些需要它的人,它是按位异或,如下所述。
之前:
boolean result = isresult();
if (result) {
result = false;
} else {
result = true;
}
后:
boolean result = isresult();
result ^= true;
这个答案出现在搜索“java反转布尔函数”时。下面的示例将防止某些静态分析工具由于分支逻辑而导致构建失败。这是有用的,如果你需要反转一个布尔值,还没有建立全面的单元测试;)
Boolean.valueOf(aBool).equals(false)
或者:
Boolean.FALSE.equals(aBool)
or
Boolean.FALSE::equals
有几个
“显而易见”的方式(对大多数人来说)
theBoolean = !theBoolean;
“最短”的路(大多数时候)
theBoolean ^= true;
“最直观”的方式(最不确定)
theBoolean = theBoolean ? false : true;
额外:在方法调用中切换和使用
theMethod( theBoolean ^= true );
由于赋值操作符总是返回已赋值的值,因此这将通过位操作符切换值,然后返回新赋值以用于方法调用。