开发者

What's the most concise way to get the inverse of a Java boolean value? [duplicate]

This question already has answers here: Clea开发者_JAVA百科nest way to toggle a boolean variable in Java? (9 answers) Closed 8 years ago.

If you have a boolean variable:

boolean myBool = true;

I could get the inverse of this with an if/else clause:

if (myBool == true)
 myBool = false;
else
 myBool = true;

Is there a more concise way to do this?


Just assign using the logical NOT operator ! like you tend to do in your condition statements (if, for, while...). You're working with a boolean value already, so it'll flip true to false (and vice versa):

myBool = !myBool;


An even cooler way (that is more concise than myBool = !myBool for variable names longer than 4 characters if you want to set the variable):

myBool ^= true;

And by the way, don't use if (something == true), it's simpler if you just do if (something) (the same with comparing with false, use the negation operator).


For a boolean it's pretty easy, a Boolean is a little bit more challenging.

  • A boolean only has 2 possible states: trueand false.
  • A Boolean on the other hand, has 3: Boolean.TRUE, Boolean.FALSE or null.

Assuming that you are just dealing with a boolean (which is a primitive type) then the easiest thing to do is:

boolean someValue = true; // or false
boolean negative = !someValue;

However, if you want to invert a Boolean (which is an object), you have to watch out for the null value, or you may end up with a NullPointerException.

Boolean someValue = null;
Boolean negativeObj = !someValue.booleanValue(); --> throws NullPointerException.

Assuming that this value is never null, and that your company or organization has no code-rules against auto-(un)boxing. You can actually just write it in one line.

Boolean someValue = Boolean.TRUE; // or Boolean.FALSE
Boolean negativeObj = !someValue;

However if you do want to take care of the null values as well. Then there are several interpretations.

boolean negative = !Boolean.TRUE.equals(someValue); //--> this assumes that the inverse of NULL should be TRUE.

// if you want to convert it back to a Boolean object, then add the following.
Boolean negativeObj = Boolean.valueOf(negative);

On the other hand, if you want null to stay null after inversion, then you may want to consider using the apache commons class BooleanUtils(see javadoc)

Boolean someValue = null; // or Boolean.TRUE or Boolean.FALSE;
Boolean negativeObj = BooleanUtils.negate(someValue);

Some prefer to just write it all out, to avoid having the apache dependency.

Boolean someValue = null; // or Boolean.TRUE or Boolean.FALSE;
Boolean negative = (someValue == null)? null : Boolean.valueOf(!someValue.booleanValue());


The most concise way is to not invert the boolean, and just use !myBool later on in the code when you want to check the opposite condition.


myBool = myBool ? false : true;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜