【发布时间】:2020-11-20 08:37:03
【问题描述】:
我正在尝试调用一种方法,该方法将按目标或胜利对 ArrayList 进行排序。我的 FootballClub 类中已经有一个 compareTo,它对有效的目标进行排序。有没有办法让我有多个 compareTo 来对不同的属性进行排序,例如在调用我的 sortGoals 或 sortWins 方法时可以调用的目标或胜利?
public class FootballClub extends SportsClub implements Comparable <FootballClub> {
int wins = 0;
int goals = 0;
int points = 0;
//other methods above
@Override
public int compareTo(FootballClub o) {
int compareGoals=((FootballClub)o).getGoals();
return this.goals-compareGoals;
}
}
【问题讨论】:
-
旁注:现有的
compareTo方法可以改进:1) 将o转换为FootballClub是多余的; 2) 一般建议使用Integer::compare而不是减法,即使整数溢出的可能性不大。所以,它可能是public int compareTo(FootballClub fc) { return Integer.compare(this.goals, fc.getGoals()); } -
哦,好的,谢谢你让我知道,不知道。我会改的
标签: java sorting arraylist compareto