##Java Comparator Interface
####Concept
Comparablesare the basic interface java offers to compare two objects- classes that implement Comparable must provide a
compareTomethod - the
compareTomethod determines what is known as the natural order in which objects of that class are sorted
- classes that implement Comparable must provide a
- comparators enable us to define a compare statement outside of a class
- this allows us to redefine sorting order to be different than the natural order
####Implementation 2 main changes must be made to use the Comparator interface: sorting methods and the comparators themselves.
1. the Comparators themselves
must be coded
-
these are classes that implement Comparator
-
the classes must contain a
public int compare()methodpublic static class ByName implements Comparator { public int compare(ClassWeAreTryingToSort a, ClassWeAreTryingToSort b) { /code that determines sorting behaviour/ } }
-
the int generally returns
-ve numberif a < b0if a == b+ve numberif a > b
2. Sorting methods
must be changed/added to allow comparators to be used
- to work with Comparators,
java.util.Comparatorshould be imported- items to be sorted must be changed from
ComparabletoObject - an extra parameter must be added to functions that handled
Comparables to take aComparator
- items to be sorted must be changed from
#####Example of such a change in the less method
Before
public static boolean less(Comparable a, Comparable b)
{
return a.compareTo(b) < 0;
}
After
public static boolean less(Object a, Object b, Comparator c)
{
return c.compare(a, b) < 0;
}