[英]Implement Comparator for primitive boolean type?
I need some classes implements Comparator
, and for one I want to compare primitive boolean
(not Boolean
) values.我需要一些类
implements Comparator
,对于其中一个我想比较原始boolean
(不是Boolean
)值。
IF it was a B oolean, I would just return boolA.compareTo(boolB);
如果它是一个布尔值,我会返回boolA.compareTo
return boolA.compareTo(boolB);
which would return 0, -1 or 1. But how can I do this with primitives?这将返回 0、-1 或 1。但是我怎样才能用原语做到这一点呢?
You can look up how it is implemented for the java.lang.Boolean
, since that class, naturally, uses a primitive boolean as well:您可以查看它是如何为
java.lang.Boolean
实现的,因为该类自然也使用原始布尔值:
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)
.从 Java 7 开始,您可以简单地使用内置静态方法
Boolean.compare(a, b)
。
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
.从 Java 7 开始, Marko Topolnik 在他的回答中展示的逻辑已经转移到另一种方法中,以公开一种比较原始
boolean
的方法。
Javadoc for Boolean.compare(boolean x, boolean y)
: Boolean.compare(boolean x, boolean y)
的 Javadoc :
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))
An even better approach and correct use of Boolean-Adapter class更好的方法和正确使用 Boolean-Adapter 类
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 use java's autoboxing feature to alleviate this problem.您可以使用 java 的自动装箱功能来缓解这个问题。 You can read about autoboxing here: Java autoboxing
您可以在此处阅读有关自动装箱的信息: Java 自动装箱
You can compare two primitive boolean values b1 and b2 in following way.您可以通过以下方式比较两个原始布尔值 b1 和 b2。
(Boolean.valueOf(b1).equals(Boolean.valueOf(b2)) (Boolean.valueOf(b1).equals(Boolean.valueOf(b2))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.