membersound
membersound

Reputation: 86747

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?

Upvotes: 21

Views: 32290

Answers (5)

Marko Topolnik
Marko Topolnik

Reputation: 200168

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

Upvotes: 33

Pwnstar
Pwnstar

Reputation: 2245

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

Upvotes: 5

mkobit
mkobit

Reputation: 47259

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

Upvotes: 13

Srikar
Srikar

Reputation: 129

You can compare two primitive boolean values b1 and b2 in following way.

(Boolean.valueOf(b1).equals(Boolean.valueOf(b2))

Upvotes: 0

Adam Arold
Adam Arold

Reputation: 30528

You can use java's autoboxing feature to alleviate this problem. You can read about autoboxing here: Java autoboxing

Upvotes: 2

Related Questions