在Java中有比简单的if-else更好的方法来否定布尔值吗?
if (theBoolean) {
theBoolean = false;
} else {
theBoolean = true;
}
在Java中有比简单的if-else更好的方法来否定布尔值吗?
if (theBoolean) {
theBoolean = false;
} else {
theBoolean = true;
}
当前回答
theBoolean = !theBoolean;
其他回答
有几个
“显而易见”的方式(对大多数人来说)
theBoolean = !theBoolean;
“最短”的路(大多数时候)
theBoolean ^= true;
“最直观”的方式(最不确定)
theBoolean = theBoolean ? false : true;
额外:在方法调用中切换和使用
theMethod( theBoolean ^= true );
由于赋值操作符总是返回已赋值的值,因此这将通过位操作符切换值,然后返回新赋值以用于方法调用。
这个答案出现在搜索“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)
如果你使用布尔NULL值,并认为它们是假的,试试这个:
static public boolean toggle(Boolean aBoolean) {
if (aBoolean == null) return true;
else return !aBoolean;
}
如果你没有处理布尔NULL值,试试这个:
static public boolean toggle(boolean aBoolean) {
return !aBoolean;
}
这些是最干净的,因为它们在方法签名中显示了意图,与!操作符,并且可以很容易地调试。
使用
boolean bTrue = true
boolean bFalse = false
boolean bNull = null
toggle(bTrue) // == false
toggle(bFalse) // == true
toggle(bNull) // == true
当然,如果你使用Groovy或允许扩展方法的语言,你可以注册一个扩展,然后简单地做:
Boolean b = false
b = b.toggle() // == true