To sort an array or a collection of objects, we need to make sure that the objects are mutually comparable.
This is supported by the Comparable interface that contains only one method:
compareTo(Object) : int
The return value of the compareTo() method is negative, zero or positive:
1. Negative when the current instance comes before the argument in the ordering.
2. Positive when the current instance comes after the argument.
3. Otherwises zero is the return value.
Keep in mind that the default equals() method compares two objects using their references (Identity comparison).
If x.equals(y) is true, then x.hashCode() must be same as y.hashCode().
Objects that implement the Comparable interface can be sorted by the sort() method of the Arrays or Collections classes
If you want to have a few different ways of comparing, pay attention to the fact that you need another class that implements the Comparator interface and compare() method takes two arguments!
import java.util.*;
public class CompareBySuitRank implements Comparator<Card> {
@Override
public int compare(Card x, Card y) {
int suitResult = x.getSuit().compareTo(y.getSuit());
if (suitResult != 0) {
return suitResult;
}
return x.getRank() - y.getRank();
}
}
List<Card> cards = new ArrayList<Card>();
cards.add(new Card("hearts", 2));
cards.add(new Card("diamonds", 2));
cards.add(new Card("spades", 3));
cards.add(new Card("clubs", 4));
cards.add(new Card("hearts", 1));
Collections.sort(cards, new CompareBySuitRank());
for (Card c : cards) {
System.out.println(c);
}
compareTo method defines the NATURAL ORDER of the type whereas compare method is used to define different custom orders of the type.