-1

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.

Zoe
  • 27,060
  • 21
  • 118
  • 148
  • 2
    Your comparator also needs to return something negative if `o1.scores.size() < o2.scores.size()` - you are not fulfilling the contract of `Comparator`. – Dawood ibn Kareem Mar 10 '19 at 19:45
  • just to second above comment, here the [documentation](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Comparator.html#compare(T,T)) of expected return value: *"a **negative integer**, zero, or a positive integer as the first argument is **less than**, equal to, or greater than the second."* – user85421 Mar 10 '19 at 20:47

2 Answers2

1

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);
}
Yassin Hajaj
  • 21,337
  • 9
  • 51
  • 89
  • 1
    or the functional alternative: `Collections.sort(games, Comparator.comparingInt(game -> game.scores.size()))` – user85421 Mar 10 '19 at 20:42
0

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