Cleanest way to toggle a boolean variable in Java?

前端 未结 9 992
悲哀的现实
悲哀的现实 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: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
    

提交回复
热议问题