问题
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?
回答1:
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));
}
回答2:
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))
回答3:
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))
回答4:
You can use java's autoboxing feature to alleviate this problem. You can read about autoboxing here: Java autoboxing
回答5:
You can compare two primitive boolean values b1 and b2 in following way.
(Boolean.valueOf(b1).equals(Boolean.valueOf(b2))
来源:https://stackoverflow.com/questions/13229592/implement-comparator-for-primitive-boolean-type