-1

我有一个游戏列表,我希望按他们的得分数量(按降序排列)进行排序。我为此目的编写了这段代码;

public void OnResponse(Object response) {
    List<Game> games = (List<Game>)response;
    Collections.sort(games, new Comparator<Game>() {
        @Override
        public int compare(Game o1, Game o2) {
            if( o1.scores.size() > o2.scores.size()) {
                return 1;
            } else {
                return 0;
            }
        }
    });
    trendingGames = games;
    gridView = view.findViewById(R.id.trendingGrid);
    gridView.setAdapter(new TrendingAdapter(games, getContext()));
    view.findViewById(R.id.progressBar).setVisibility(View.GONE);
}

但是,当我检查调试器时,我发现列表根本没有改变。

4

2 回答 2

1

你可以用它Integer#compare来缓解你的生活并确保你的Comparator合同得到尊重

@Override
public int compare(Game o1, Game o2) {
    int score1 = o1.scores.size();
    int score2 = o2.scores.size();
    return Integer.compare(score1, score2);
}
于 2019-03-10T19:48:42.057 回答
0

这将起作用:

public class Game implements Comparable<Game> {

int score;

public Game(int score) {
    this.score = score;
}

public int getScore() {
    return score;
}

public void setScore(int score) {
    this.score = score;
}

@Override
public int compareTo(Game anotherGame) {
    return Integer.compare(this.score, anotherGame.getScore());
}
}

public static void main(String[] args) {
    ArrayList<Game> games = new ArrayList<>();
    games.add(new Game(5));
    games.add(new Game(4));
    games.add(new Game(1));
    games.add(new Game(9));
    Collections.sort(games);
    Collections.reverse(games);
}
于 2019-03-10T21:42:16.920 回答