在 Java 中切换布尔变量的最简洁方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/224311/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 11:40:46  来源:igfitidea点击:

Cleanest way to toggle a boolean variable in Java?

javaboolean

提问by Kevin Griffin

Is there a better way to negate a boolean in Java than a simple if-else?

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

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

采纳答案by Aaron Maenpaa

theBoolean = !theBoolean;

回答by Aaron Maenpaa

theBoolean ^= true;

Fewer keystrokes if your variable is longer than four letters

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

Edit: code tends to return useful results when used as Google search terms. The code above doesn't. For those who need it, it's bitwise XORas described here.

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

回答by Nikhil Kumar

Before:

前:

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

After:

后:

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

回答by Levite

There are several

有几种

The "obvious" way(for most people)

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

theBoolean = !theBoolean;

The "shortest" way(most of the time)

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

theBoolean ^= true;

The "most visual" way(most uncertainly)

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

theBoolean = theBoolean ? false : true;

Extra: Toggle and use in a method call

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

theMethod( theBoolean ^= true );

Since the assignment operator always returns what has been assigned, this will toggle the value via the bitwise operator, and then return the newly assigned value to be used in the method call.

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

回答by Steven Spungin

If you use Boolean NULL values and consider them false, try this:

如果您使用布尔 NULL 值并认为它们是错误的,请尝试以下操作:

static public boolean toggle(Boolean aBoolean) {
    if (aBoolean == null) return true;
    else return !aBoolean;
}

If you are not handing Boolean NULL values, try this:

如果您不处理布尔 NULL 值,请尝试以下操作:

static public boolean toggle(boolean aBoolean) {
   return !aBoolean;
}

These are the cleanestbecause they show the intent in the method signature, are easier to read compared to the !operator, and can be easily debugged.

这些是最干净的,因为它们在方法签名中显示了意图,与! 运算符,并且可以轻松调试。

Usage

用法

boolean bTrue = true
boolean bFalse = false
boolean bNull = null

toggle(bTrue) // == false
toggle(bFalse) // == true
toggle(bNull) // == true

Of course, if you use Groovyor a language that allows extension methods, you can register an extension and simply do:

当然,如果您使用Groovy或允许扩展方法的语言,您可以注册一个扩展并简单地执行以下操作:

Boolean b = false
b = b.toggle() // == true

回答by Will D.

If you're not doing anything particularly professional you can always use a Util class. Ex, a util class from a project for a class.

如果您没有做任何特别专业的事情,您可以随时使用 Util 类。例如,一个类项目中的一个 util 类。

public class Util {


public Util() {}
public boolean flip(boolean bool) { return !bool; }
public void sop(String str) { System.out.println(str); }

}

then just create a Util object Util u = new Util();and have something for the return System.out.println( u.flip(bool) );

然后只需创建一个 Util 对象 Util u = new Util();并返回一些东西System.out.println( u.flip(bool) );

If you're gonna end up using the same thing over and over, use a method, and especially if it's across projects, make a Util class. Dunno what the industry standard is however. (Experienced programmers feel free to correct me)

如果您最终要一遍又一遍地使用相同的东西,请使用一种方法,特别是如果它是跨项目的,请创建一个 Util 类。然而,不知道行业标准是什么。(有经验的程序员欢迎指正)

回答by Doctor Parameter

This answer came up when searching for "java invert boolean function". The example below will prevent certain static analysis tools from failing builds due to branching logic. This is useful if you need to invert a boolean and haven't built out comprehensive unit tests ;)

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

Boolean.valueOf(aBool).equals(false)

or alternatively:

或者:

Boolean.FALSE.equals(aBool)

or

或者

Boolean.FALSE::equals