Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 599
membersound Avatar asked Nov 05 '12 09:11

membersound


People also ask

How do you compare two boolean objects?

Boolean compare() method in Java with Examples Parameters: It takes two boolean values a and b in the parameter which are to be compared. 0 if 'a' is equal to 'b', a negative value if 'a'is false and 'b' is true, a positive value if 'a' is true and 'b' is false.

Can you compare two Booleans?

We use the compare() method of the BooleanUtils class to compare two boolean values. The method takes two values and returns true if both the values are the same. Otherwise, it returns false .

What is primitive boolean?

The simplest data type available to you in Java is the primitive type boolean. A boolean variable has only two possible values, true or false, which are represented with reserved words.


1 Answers

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

like image 159
Marko Topolnik Avatar answered Oct 18 '22 12:10

Marko Topolnik