Search code examples
javacomparatorprimitive-types

Implement Comparator for primitive boolean type?


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?


Solution

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