简体   繁体   English

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

[英]Cleanest way to toggle a boolean variable in Java?

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;
}
theBoolean = !theBoolean;
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.编辑:当用作 Google 搜索词时,代码往往会返回有用的结果。 The code above doesn't.上面的代码没有。 For those who need it, it's bitwise XOR as described here .对于那些需要它的人,它是按位异或如here所述

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

This answer came up when searching for "java invert boolean function".这个答案是在搜索“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 ;)如果您需要反转布尔值并且尚未构建全面的单元测试,这将非常有用;)

Boolean.valueOf(aBool).equals(false)

or alternatively:或者:

Boolean.FALSE.equals(aBool)

or或者

Boolean.FALSE::equals

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 cleanest because 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 Groovy or a language that allows extension methods, you can register an extension and simply do:当然,如果您使用Groovy或允许扩展方法的语言,您可以注册一个扩展并简单地执行以下操作:

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

The class BooleanUtils supportes the negation of a boolean. BooleanUtils类支持布尔值的否定。 You find this class in commons-lang:commons-lang你可以在commons-lang:commons-lang 中找到这个类

BooleanUtils.negate(theBoolean)

If you're not doing anything particularly professional you can always use a Util class.如果您没有做任何特别专业的事情,您可以随时使用 Util 类。 Ex, a util class from a project for a class.例如,来自一个类的项目的 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();然后只需创建一个 Util 对象Util u = new Util(); and have something for the return System.out.println( u.flip(bool) );并有一些返回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.如果您最终要一遍又一遍地使用相同的东西,请使用一种方法,特别是如果它是跨项目的,请创建一个 Util 类。 Dunno what the industry standard is however.然而,不知道行业标准是什么。 (Experienced programmers feel free to correct me) (有经验的程序员欢迎指正)

Unfortunately, there is no short form like numbers have increment/decrement:不幸的是,没有像数字有递增/递减的简短形式:

i++;我++;

I would like to have similar short expression to invert a boolean, dmth like:我想有类似的短表达式来反转布尔值,dmth,例如:

isEmpty!;是空的!;

Before:前:

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

After:后:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM