Hearen/stackoverflow

Comparable

Closed this issue · 2 comments

Comparable is a generic interface and we have to use it as:

public class Player implements Comparable<Player> {
     
    //...
    @Override
    public int compareTo(Player otherPlayer) {
        return (this.getRanking() - otherPlayer.getRanking());
    }
}

Collections.sort(players);

In Java 8, we can use more flexible method by Comparator as:

Comparator<Player> byRanking 
 = (Player player1, Player player2) -> player1.getRanking() - player2.getRanking();


Collections.sort(players, byRanking);

// Or more terse way as
// Collections.sort(players, Comparator.comparing(Player::getRank));

The Comparable interface is a good choice when used for defining the default ordering or, in other words, if it’s the main way of comparing objects.

But using Comparator we can do more flexible things (even some impossible things when the source code is out of our control).

Some typical cases and tricky cases?