Comparable interface
The Comparable interface defines the natural ordering of a type. Suppose you have a list of String or Integer objects; you can pass this list to
Collections.sort(list);
and you will have a sorted list. How? Because String and Integer implement the Comparable interface, and implementations of the Comparable interface provide a natural order. This is similar to a class definition: " If you find a collection of objects of my type, order them according to the strategy that I defined in the compareTo method ."
Now that you define your own type, you can define the natural order of the objects in your class by implementing the Comparable interface. See the Java documentation for more information on organizing objects .
Comparator interface
The Comparator interface describes how to define custom strategies for organizing objects. Suppose we have a simple Person type, as shown below:
public class Person { String name; public Person(String name) { this.name = name; } public String getName() { return name; } }
Now, implementing the Comparator interface, you can write different strategies for ordering instances of your Person type. For example, consider two strategies for organizing Person objects, as shown below:
class StrategyOne implements Comparator<Person> { @Override public int compare(Person p1, Person p2) { return p1.getName().length() - p2.getName().length(); } } class StrategyTwo implements Comparator<Person> { @Override public int compare(Person p1, Person p2) { return p1.getName().compareTo(p2.getName()); } }
Here StrategyOne will order Person objects based on the length of their names, and StrategyTwo will order Person objects based on the lexicographic ordering of their names.
Comparator Implementation Methods
As you can see, specific strategy classes are stateless, so all instances are functionally equivalent. Thus, we need only one instance of any particular strategy class. Thus, it must be singleton. Using anonymous classes will create a new instance each time a call is made. Consider storing the object in a closed static destination field and reusing it using static factory methods to access them . For example, you can reuse the two above strategies:
class Strategies { private static final Comparator<Person> PERSON_NAME_LENGTH_COMPARATOR = new StrategyOne(); private static final Comparator<Person> PERSON_NAME_LEXICAL_COMPARATOR = new StrategyTwo(); public static Comparator<Person> personNameLengthComparator(){ return PERSON_NAME_LENGTH_COMPARATOR; } public static Comparator<Person> personNameLexicalComparator(){ return PERSON_NAME_LEXICAL_COMPARATOR; } }
Summary
To summarize, the Comparable interface Comparable used to determine the natural ordering of the class, and the Comparator interface is used to define specific strategies for ordering objects.