Java 使用Comparator对ArrayList进行排序
我遇到了一点问题。我正在使用ArrayList创建一个足球联赛表格。现在我需要做的是使用ClubPoints对ArrayList进行排序。我尝试使用一个比较器,但不确定从这里开始到哪里。谢谢你的帮助Java 使用Comparator对ArrayList进行排序,java,arraylist,comparator,Java,Arraylist,Comparator,我遇到了一点问题。我正在使用ArrayList创建一个足球联赛表格。现在我需要做的是使用ClubPoints对ArrayList进行排序。我尝试使用一个比较器,但不确定从这里开始到哪里。谢谢你的帮助 ArrayList<FootballClub> newClub = new ArrayList<FootballClub>(); String format = "|%1$-15s|%2$-15s|%3$-15s|%4$-15s|%5$-15s|%6$-15s|%7$
ArrayList<FootballClub> newClub = new ArrayList<FootballClub>();
String format = "|%1$-15s|%2$-15s|%3$-15s|%4$-15s|%5$-15s|%6$-15s|%7$-15s|%8$-15s|%9$-15s|\n";
System.out.format(format, "Score", "Name", "Location", "Wins", "Losses", "Draws",
"Goals Received", "Goals Scored", "Games Played");
for(int x = 0; x < newClub.size(); x++){
Collections.sort(newClub, new DescendingByPointsComparator());
System.out.format(format, newClub.get(x).ClubScore, newClub.get(x).ClubName, newClub.get(x).ClubLocation,
newClub.get(x).ClubWins, newClub.get(x).ClubLosses, newClub.get(x).ClubDraws, newClub.get(x).GoalsReceived,
newClub.get(x).GoalsScored, newClub.get(x).ClubGamesPlayed);
}
class DescendingByPointsComparator implements Comparator<FootballClub> {
@Override
public int compare(FootballClub lhs, FootballClub rhs) {
return Integer.compare(rhs.getPoints(), lhs.getPoints());
}
}
ArrayList newClub=new ArrayList();
字符串格式=“|%1$-15s |%2$-15s |%3$-15s |%4$-15s |%5$-15s |%6$-15s |%7$-15s |%8$-15s |%9$-15s |\n”;
系统输出格式(格式,“分数”、“姓名”、“位置”、“赢”、“输”、“平局”,
“进球数”、“进球数”、“比赛次数”);
对于(int x=0;x
在您的足球俱乐部
模型类中,您可以覆盖以下方法以实现所需:
public int compareTo(FootballClub anotherFootballClub){
// Your comparison logic here
return //negative integer if this instance is lesser and vice versa
}
另外,请确保您的
足球俱乐部
类实现了可比性
您现在拥有的有什么问题吗?我在类DerningByPoints Comparator“找不到符号:方法getPoints()”中得到一个错误,那么足球俱乐部
的定义似乎是相关的,否?请注意,在for循环中没有排序点,这很奇怪,您可能希望在循环之外排序如果“FootballClub类实现了Comparable”,则无需指定比较器。。