##Java Comparator Interface
####Concept
Comparables
are the basic interface java offers to compare two objects- classes that implement Comparable must provide a
compareTo
method - the
compareTo
method 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 number
if a < b0
if a == b+ve number
if a > b
2. Sorting methods
must be changed/added to allow comparators to be used
- to work with Comparators,
java.util.Comparator
should be imported- items to be sorted must be changed from
Comparable
toObject
- an extra parameter must be added to functions that handled
Comparable
s 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;
}