クラスを作成し、2 つのコンパレータを追加します。
class Team{
private String teamName;
private int leaguePoints;
public static final Comparator<Team> BY_NAME = new ByName();
public static final Comparator<Team> BY_POINTS = new ByPoints();
private static class ByName implements Comparator<Team>
{
public int compare(Team a, Team b)
return a.name.compareTo(b.name);
}
private static class ByPoints implements Comparator<Team>
{
public int compare(Team a, Team b)
return a.leaguePoints - b.leaguePoints;
}
}
次に、このクラスの配列を並べ替えるには、BY_NAME
最初にコンパレータを使用し、次にを使用しBY_POINTS
ます。
Arrays.sort(array, Team.BY_NAME);
Arrays.sort(array, Team.BY_POINTS);
等しいキーの相対的な順序を維持するために、必ず安定した並べ替えを使用してください (つまり、ポイントが等しい場合、選択並べ替えのような不安定な並べ替えがチーム名の並べ替え順序を台無しにする可能性があります)。