按多个字段对对象数组进行排序

Dav*_*ton 2 java sorting

假设我有一个数组,其中包含10个对象,每个对象有3个值,应该代表一个联赛表

Team1 20 5
Team2 21 6
Team3 21 8
Team4 23 8
Run Code Online (Sandbox Code Playgroud)

我想按第一个值(点)排序,然后按第二个值(目标差异)排序.

Arrays.sort()如果我覆盖compareto()并编写一段自定义代码,它将起作用.

有更简单的方法吗?通过转换为列表等?

Dun*_*nes 9

创建一个Comparator是解决这个问题的正确方法.无论你是否使用Arrays.sort()Collections.sort()取决于你.

我建议前者避免转换为列表,因此更可取.

我建议你不要通过Comparable在你的对象中实现来解决这个问题,因为这听起来像一个显示问题,并且在对象本身中嵌入一个排序顺序可能并不明智.


示例(未经测试)实现可能是:

public class ExampleComparator implements Comparator<YourObject> {

  public int compare(YourObject o1, YourObject o2) {
    if (o1 == null || o2 == null) {
      throw new NullPointerException();
    }

    if (o1.getValue1() != o2.getValue1()) {
      return Integer.compare(o1.getValue1(), o2.getValue1());
    }

    return Integer.compare(o1.getValue2(), o2.getValue2());
  }
}
Run Code Online (Sandbox Code Playgroud)