在列表

时间:2018-03-24 17:01:58

标签: java

我有一张联赛表,显示了联盟中球队的联赛排名。 此数据源自Firebase,我有一个定义列表的自定义对象。

我遇到的挑战是我还需要在返回的列表数组(leagueList)中添加一个额外的值。 firebase数据库不具备排名(第1,第2,第3,第4等......),因为联盟决定按分数排队。 我需要添加第1,第2,第3,第4等......此外。

我是否在定义列表的类中执行此操作?或者我是否必须编写一些额外的处理代码,以便在下面添加leagueList;

for (DataSnapshot matchSnapshot : dataSnapshot.getChildren()) {
    league_List match = matchSnapshot.getValue(league_List.class);
    leagueList.add(match);
}

描述列表定义的类是:

public class league_List {

    String teamName;
    Integer played;
    Integer goalsScored;
    Integer goalsConceded;
    Integer points;

    public league_List(Integer rankNo) {

    }

    public league_List(String teamName, Integer played, Integer goalsScored, Integer goalsConceded, Integer points) {
        this.teamName = teamName;
        this.played = played;
        this.goalsScored = goalsScored;
        this.goalsConceded = goalsConceded;
        this.points = points;
    }

    public String getTeamName() {
        return teamName;
    }

    public Integer getPlayed() {
        return played;
    }

    public Integer getGoalsScored() {
        return goalsScored;
    }

    public Integer getGoalsConceded() {
        return goalsConceded;
    }

    public Integer getPoints() {
        return points;
    }

}

1 个答案:

答案 0 :(得分:0)

您应该将league_List课程重命名为Team(因为这似乎是这样),并且您的leagueList应该是Teams

您的Team类应该具有排名属性,这样:

class Team {

    String teamName;
    Integer played;
    Integer goalsScored;
    Integer goalsConceded;
    Integer points;
    int rank;

    public Team() {}

    public Team(String teamName, Integer played, Integer goalsScored, Integer goalsConceded, Integer points) {
        this.teamName = teamName;
        this.played = played;
        this.goalsScored = goalsScored;
        this.goalsConceded = goalsConceded;
        this.points = points;
    }

    // Getters/Setters    

}

然后你可以这样做你的程序:

private List<Team> leagueList = new ArrayList<>();

// Get all your teams
for (DataSnapshot matchSnapshot : dataSnapshot.getChildren()) {
    Team team = matchSnapshot.getValue(Team.class);
    leagueList.add(team);
}

// Sort the teams by points
leagueList.sort(Comparator.comparing(Team::getPoints));

// Give each team its rank
for(int i=leagueList.size(); i>0; i--) {
    leagueList.get(i-1).setRank(i);
}

更好的方法是拥有League对象,其中包含Team列表和排名。这样团队本身就不知道它的等级。这将是League

的关注点