229

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

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

9 回答 9

580
theBoolean = !theBoolean;
于 2008-10-22T02:45:16.757 回答
179
theBoolean ^= true;

如果您的变量长于四个字母,则击键次数更少

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

于 2008-10-22T03:28:55.153 回答
47

有几种

“明显”的方式(对大多数人来说)

theBoolean = !theBoolean;

“最短”的方式(大部分时间)

theBoolean ^= true;

“最直观”的方式(最不确定)

theBoolean = theBoolean ? false : true;

额外:在方法调用中切换和使用

theMethod( theBoolean ^= true );

由于赋值运算符总是返回已分配的内容,这将通过按位运算符切换值,然后返回新分配的值以在方法调用中使用。

于 2016-11-14T16:58:57.963 回答
5

搜索“java invert boolean function”时出现了这个答案。下面的示例将防止某些静态分析工具由于分支逻辑而导致构建失败。如果您需要反转布尔值并且没有构建全面的单元测试,这很有用;)

Boolean.valueOf(aBool).equals(false)

或者:

Boolean.FALSE.equals(aBool)

或者

Boolean.FALSE::equals
于 2019-08-16T01:27:46.963 回答
2

如果您使用布尔 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
于 2017-07-01T13:51:41.627 回答
1

该类BooleanUtils支持布尔值的否定。你可以在commons-lang:commons-lang中找到这个类

BooleanUtils.negate(theBoolean)
于 2020-06-04T15:24:39.353 回答
-1

如果你没有做任何特别专业的事情,你总是可以使用 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 类。不知道行业标准是什么。(有经验的程序员欢迎指正)

于 2019-04-11T17:37:49.990 回答
-2

不幸的是,没有像数字一样具有递增/递减的简短形式:

我++;

我希望有类似的简短表达式来反转布尔值,dmth,例如:

是空的!;

于 2020-08-05T23:07:21.297 回答
-4

前:

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

后:

boolean result = isresult();
result ^= true;
于 2015-04-02T09:49:38.663 回答