Hearen / AllInJava

Everything about Java I know and should know.
GNU General Public License v3.0
0 stars 0 forks source link

Comparable & Comparator #95

Open Hearen opened 5 years ago

Hearen commented 5 years ago

Comparable

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

Comparator

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).

Hearen commented 5 years ago

52