I need some classes implements Comparator
, and for one I want to compare primitive boolean
(not Boolean
) values.
IF it was a Boolean, I would just return boolA.compareTo(boolB);
which would return 0, -1 or 1. But how can I do this with primitives?
Boolean compare() method in Java with Examples Parameters: It takes two boolean values a and b in the parameter which are to be compared. 0 if 'a' is equal to 'b', a negative value if 'a'is false and 'b' is true, a positive value if 'a' is true and 'b' is false.
We use the compare() method of the BooleanUtils class to compare two boolean values. The method takes two values and returns true if both the values are the same. Otherwise, it returns false .
The simplest data type available to you in Java is the primitive type boolean. A boolean variable has only two possible values, true or false, which are represented with reserved words.
You can look up how it is implemented for the java.lang.Boolean
, since that class, naturally, uses a primitive boolean as well:
public int compareTo(Boolean b) {
return (b.value == value ? 0 : (value ? 1 : -1));
}
As of Java 7 you can simply use the built-in static method Boolean.compare(a, b)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With