CompareTo方法哪种用法更容易理解?
我想根据布尔值对对象进行排序,并且我想将真值排序在假值之前。
这些compareTo 的实现中哪一个更具可读性?
使用 -1 更改默认行为
public class Example implements Comparable<Example>{
Boolean isOk;
public int compareTo(Example o) {
return -1 * this.isOk.compareTo(o.isOk);
}
}
或交换 Boolean#compareTo 方法的两侧?
public class ExampleTwo implements Comparable<ExampleTwo>{
Boolean isOk;
public int compareTo(ExampleTwo o) {
return o.isOk.compareTo(this.isOk);
}
}
I want to sort objects based on Boolean values and I want to sort true values before false values.
Which of these implementations of compareTo is more readable?
Using -1 to change default behavior
public class Example implements Comparable<Example>{
Boolean isOk;
public int compareTo(Example o) {
return -1 * this.isOk.compareTo(o.isOk);
}
}
or swap sides of Boolean#compareTo method?
public class ExampleTwo implements Comparable<ExampleTwo>{
Boolean isOk;
public int compareTo(ExampleTwo o) {
return o.isOk.compareTo(this.isOk);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
第一种形式完全是错误的 - 因为如果
compareTo
返回Integer.MIN_VALUE
,它会尝试否定该结果 - 并导致Integer再次.MIN_VALUE
。解决这个问题最简单的方法就是使用第二个片段中的代码。
另一方面:
isOk
为 null,则两者都可能失败布尔值可能。 compareTo
永远不会返回Integer.MIN_VALUE
。但我不会依赖这一点。The first form is simply wrong - because if
compareTo
returnsInteger.MIN_VALUE
, it will try to negate that - and result inInteger.MIN_VALUE
again.The easiest way to fix that is just to use the code from the second snippet.
On the other hand:
isOk
is nullBoolean.compareTo
will never returnInteger.MIN_VALUE
. I wouldn't rely on that though.我会使用
从
Guava(以前的 Google Collections),它实现了
Comparator
,因此可以使用作为直接替代品:I'd use the
Ordering
class from Guava (formerly Google Collections), it implementsComparator
, so it can be used as a drop-in replacement: