CompareTo方法哪种用法更容易理解?

发布于 2024-09-06 02:36:26 字数 519 浏览 2 评论 0原文

我想根据布尔值对对象进行排序,并且我想将真值排序在假值之前。

这些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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

夢归不見 2024-09-13 02:36:27

第一种形式完全是错误的 - 因为如果 compareTo 返回 Integer.MIN_VALUE,它会尝试否定该结果 - 并导致 Integer再次.MIN_VALUE

解决这个问题最简单的方法就是使用第二个片段中的代码。

另一方面:

  • 如果 isOk 为 null,则两者都可能失败
  • 如果您确实只使用布尔值,那么简单的真值表可能会更简单
  • 布尔值可能。 compareTo 永远不会返回 Integer.MIN_VALUE。但我不会依赖这一点。

The first form is simply wrong - because if compareTo returns Integer.MIN_VALUE, it will try to negate that - and result in Integer.MIN_VALUE again.

The easiest way to fix that is just to use the code from the second snippet.

On the other hand:

  • Both could fail if isOk is null
  • If you're really only using Booleans, a simple truth table may be simpler
  • It's possible that Boolean.compareTo will never return Integer.MIN_VALUE. I wouldn't rely on that though.
放血 2024-09-13 02:36:27

我会使用 Guava(以前的 Google Collections),它实现了 Comparator,因此可以使用作为直接替代品:

Ordering<Object> reverseOrdering = Ordering.natural().reverse();

I'd use the Ordering class from Guava (formerly Google Collections), it implements Comparator, so it can be used as a drop-in replacement:

Ordering<Object> reverseOrdering = Ordering.natural().reverse();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文