有没有比简单的 if-else 更好的方法来否定 Java 中的布尔值?
if (theBoolean) {
theBoolean = false;
} else {
theBoolean = true;
}
theBoolean = !theBoolean;
“明显”的方式(对大多数人来说)
theBoolean = !theBoolean;
“最短”的方式(大部分时间)
theBoolean ^= true;
“最直观”的方式(最不确定)
theBoolean = theBoolean ? false : true;
theMethod( theBoolean ^= true );
由于赋值运算符总是返回已分配的内容,这将通过按位运算符切换值,然后返回新分配的值以在方法调用中使用。
搜索“java invert boolean function”时出现了这个答案。下面的示例将防止某些静态分析工具由于分支逻辑而导致构建失败。如果您需要反转布尔值并且没有构建全面的单元测试,这很有用;)
Boolean.valueOf(aBool).equals(false)
或者:
Boolean.FALSE.equals(aBool)
或者
Boolean.FALSE::equals
如果您使用布尔 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
该类BooleanUtils
支持布尔值的否定。你可以在commons-lang:commons-lang中找到这个类
BooleanUtils.negate(theBoolean)
如果你没有做任何特别专业的事情,你总是可以使用 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 类。不知道行业标准是什么。(有经验的程序员欢迎指正)
不幸的是,没有像数字一样具有递增/递减的简短形式:
我++;
我希望有类似的简短表达式来反转布尔值,dmth,例如:
是空的!;
前:
boolean result = isresult();
if (result) {
result = false;
} else {
result = true;
}
后:
boolean result = isresult();
result ^= true;