简体   繁体   English

Collections.sort 不会改变列表

[英]Collections.sort does not change list

I have a list of games that I wish to sort by the number of scores they have (in descending order).我有一个游戏列表,我希望按照它们的得分数量(按降序排列)进行排序。 I wrote this code for this purpose;我为此目的编写了这段代码;

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

However, when I check the debugger I see that the list does not change at all.但是,当我检查调试器时,我发现列表根本没有改变。

You could use Integer#compare to ease your life and make sure your Comparator contract is respected您可以使用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);
}

This will work:这将起作用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM