Cleanest way to toggle a boolean variable in Java?

匿名 (未验证) 提交于 2019-12-03 02:45:02

问题:

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

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

回答1:

theBoolean = !theBoolean; 


回答2:

theBoolean ^= true; 

Fewer keystrokes if your variable is longer than four letters



回答3:

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.



回答4:

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

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

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

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:

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


回答5:

Before:

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

After:

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


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!