Collections.sort does not change list

423 Views Asked by At

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.

2

There are 2 best solutions below

1
On BEST ANSWER

You could use Integer#compare to ease your life and make sure your Comparator contract is respected

@Override
public int compare(Game o1, Game o2) {
    int score1 = o1.scores.size();
    int score2 = o2.scores.size();
    return Integer.compare(score1, score2);
}
0
On

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