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?
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)
.
Since Java 7, the logic that Marko Topolnik showed in his answer has moved into another method to expose a way to compare primitive boolean
.
Javadoc for Boolean.compare(boolean x, boolean y)
:
public static int compare(boolean x, boolean y)
Compares two boolean values. The value returned is identical to
what would be returned by:
Boolean.valueOf(x).compareTo(Boolean.valueOf(y))
An even better approach and correct use of Boolean-Adapter class
public int compare(boolean lhs, boolean rhs) {
return Boolean.compare(lhs, rhs);
}
EDIT:
Hint: This sorts the "false" values first. If you want to invert the sorting use:
(-1 * Boolean.compare(lhs, rhs))
You can use java's autoboxing feature to alleviate this problem. You can read about autoboxing here: Java autoboxing
You can compare two primitive boolean values b1 and b2 in following way.
(Boolean.valueOf(b1).equals(Boolean.valueOf(b2))