使用Comparator对ArrayList进行排序

时间:2014-11-15 19:39:50

标签: 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$-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());
    }
}

1 个答案:

答案 0 :(得分:0)

FootballClub模型类中,您可以覆盖以下方法以实现您想要的效果:

public int compareTo(FootballClub anotherFootballClub){

    // Your comparison logic here
    return //negative integer if this instance is lesser and vice versa
}

另外,请确保您的FootballClub班级实施Comparable