Comparator can be used to compare the objects of a class that doesn’t implement Comparable. You have learned how to compare elements using the Comparable interface (the section). Several classes in the Java API, such as String, Date, Calendar, BigInteger, BigDecimal, and all the numeric wrapper classes for the primitive types, implement the Comparable interface. The Comparable interface defines the compareTo method, which is used to compare two elements of the same class that implement the Comparable interface.
What if the elements’ classes do not implement the Comparable interface? Can these elements be compared? You can define a comparator to compare the elements of different classes. To do so, define a class that implements the java.util.Comparator interface and overrides its compare method.
public int compare(T element1, T element2)
Returns a negative value if element1 is less than element2, a positive value if element1 is greater than element2, and zero if they are equal.
The GeometricObject class was introduced in the section, Abstract Classes. The GeometricObject class does not implement the Comparable interface. To compare the objects of the GeometricObject class, you can define a comparator class, as shown in the code below.
Line 4 implements Comparator. Line 5 overrides the compare method to compare two geometric objects. The class also implements Serializable. It is generally a good idea for comparators to implement Serializable, as they may be used as ordering methods in serializable data structures. In order for the data structure to serialize successfully, the comparator (if provided) must implement Serializable.
The code below gives a method that returns a larger object between two geometric objects. The objects are compared using the GeometricObjectComparator.
The program creates a Rectangle and a Circle object in lines 7–8 (the Rectangle and Circle classes were defined in the section, Abstract Classes). They are all subclasses of GeometricObject. The program invokes the max method to obtain the geometric object with the larger area (lines 10).
The GeometricObjectComparator is created and passed to the max method (line 10) and this comparator is used in the max method to compare the geometric objects in line 16.
Comparable is used to compare the objects of the class that implement Comparable. Comparator can be used to compare the objects of a class that doesn’t implement Comparable.
Comparing elements using the Comparable interface is referred to as comparing using natural order, and comparing elements using the Comparator interface is referred to as comparing using comparator.