Collections.sort 不更改列表

Collections.sort does not change list

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

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);
}

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

您可以使用 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);
}

这将起作用:

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);
}