【问题标题】:Using Comparator to sort an ArrayList使用 Comparator 对 ArrayList 进行排序
【发布时间】:2014-11-15 19:39:49
【问题描述】:

我遇到了一些问题。我使用 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());
    }
}

【问题讨论】:

  • 你现在有什么问题?
  • 在 DescendingByPointsComparator 类中出现错误“找不到符号:方法 getPoints()”
  • 那么FootballClub 的定义似乎是相关的,不是吗?
  • 请注意,in for 循环没有意义,奇怪的是您可能想在循环外进行排序

标签: java arraylist comparator


【解决方案1】:

在您的FootballClub 模型类中,您可以重写以下方法来实现您想要的:

public int compareTo(FootballClub anotherFootballClub){

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

另外,确保您的 FootballClub 类实现 Comparable

【讨论】:

  • 如果“FootballClub 类实现 Comparable”,则无需指定 Comparator..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多