题
是否有更好的方法来否定Java中的布尔值而不是简单的if-else?
if (theBoolean) {
theBoolean = false;
} else {
theBoolean = true;
}
解决方案
theBoolean = !theBoolean;
其他提示
theBoolean ^= true;
如果您的变量超过四个字母
,则击键次数减少有几个
“明显”的方式(对大多数人来说)
theBoolean = !theBoolean;
“最短”的方式(大部分时间)
theBoolean ^= true;
“最具视觉效果”方式(最不确定)
theBoolean = theBoolean ? false : true;
额外:在方法调用中切换并使用
theMethod( theBoolean ^= true );
由于赋值运算符始终返回已分配的内容,因此将通过按位运算符切换值,然后返回要在方法调用中使用的新分配值。
如果您使用布尔值NULL并将其视为false,请尝试以下操作:
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
如果您没有做任何特别专业的事情,您可以随时使用Util课程。例如,一个类的项目的util类。
public class Util {
public Util() {}
public boolean flip(boolean bool) { return !bool; }
public void sop(String str) { System.out.println(str); }
}
然后只需创建一个Util对象
Util u = new Util();
返回 System.out.println(u.flip(bool));
如果你最终会反复使用相同的东西,请使用方法,特别是如果它跨越项目,请创建一个Util类。然而,不知道行业标准是什么。 (有经验的程序员可以随意纠正我)
之前:
boolean result = isresult();
if (result) {
result = false;
} else {
result = true;
}
后:
boolean result = isresult();
result ^= true;
不隶属于 StackOverflow