问题
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?
回答1:
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;
回答2:
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).
回答3:
For a boolean it's pretty easy, a Boolean is a little bit more challenging.
- A
booleanonly has 2 possible states:trueandfalse. - A
Booleanon the other hand, has 3:Boolean.TRUE,Boolean.FALSEornull.
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 : !someValue.booleanValue();
Boolean negativeObj = Boolean.valueOf(negative);
回答4:
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.
回答5:
myBool = myBool ? false : true;
来源:https://stackoverflow.com/questions/3907384/whats-the-most-concise-way-to-get-the-inverse-of-a-java-boolean-value