Implement Comparator for primitive boolean type?

membersound picture membersound · Nov 5, 2012 · Viewed 22.5k times · Source

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?

Answer

Marko Topolnik picture Marko Topolnik · Nov 5, 2012

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).