Implement Comparator for primitive boolean type?

落爺英雄遲暮 提交于 2019-12-04 23:05:36

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));
}
mkobit

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

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

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

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!