Cleanest way to toggle a boolean variable in Java?

前端 未结 9 918
悲哀的现实
悲哀的现实 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条回答
  •  -上瘾入骨i
    2020-11-27 10:43

    Before:

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

    After:

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

提交回复
热议问题