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

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

当前回答

之前:

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
theBoolean ^= true;

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

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

之前:

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

后:

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

如果你做的不是特别专业,你可以使用Util类。Ex,来自项目的一个用于类的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(); 准备好返回系统的东西,完毕。Println (u.flip(bool));

如果你要反复使用相同的东西,使用一个方法,特别是在跨项目时,创建一个Util类。然而,不知道行业标准是什么。(有经验的程序员可以随意纠正我)