Cleanest way to toggle a boolean variable in Java?

前端 未结 9 818
悲哀的现实
悲哀的现实 2020-11-27 10:03

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

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


        
相关标签:
9条回答
  • 2020-11-27 10:27

    The class BooleanUtils supportes the negation of a boolean. You find this class in commons-lang:commons-lang

    BooleanUtils.negate(theBoolean)
    
    0 讨论(0)
  • 2020-11-27 10:33

    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
    
    0 讨论(0)
  • 2020-11-27 10:37

    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:

    isEmpty!;

    0 讨论(0)
  • 2020-11-27 10:40
    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 XOR as described here.

    0 讨论(0)
  • 2020-11-27 10:43

    Before:

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

    After:

    boolean result = isresult();
    result ^= true;
    
    0 讨论(0)
  • 2020-11-27 10:44

    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 ;)

    Boolean.valueOf(aBool).equals(false)
    

    or alternatively:

    Boolean.FALSE.equals(aBool)
    

    or

    Boolean.FALSE::equals
    
    0 讨论(0)
提交回复
热议问题