Java Reference
In-Depth Information
Comparator
can be used to compare the objects of a class that doesn't implement
Comparable
.
Key
Point
You have learned how to compare elements using the
Comparable
interface (introduced
in Section 13.6). 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<T>
interface
and overrides its
compare
method.
comparator
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 Section 13.2, 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
Listing 20.4.
L
ISTING
20.4
GeometricObjectComparator.java
1
import
java.util.Comparator;
2
3
public class
GeometricObjectComparator
4
implements
Comparator<GeometricObject>, java.io.Serializable {
implements
Comparator
implements
compare
5
public int
compare(GeometricObject o1, GeometricObject o2) {
6
double
area1 = o1.getArea();
7
double
area2 = o2.getArea();
8
9
if
(area1 < area2)
10
return
-1
;
11
else if
(area1 == area2)
12
return
0
;
13
else
14
return
1
;
15 }
16 }
Line 4 implements
Comparator<GeometricObject>
. 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
.
Listing 20.5 gives a method that returns a larger object between two geometric objects. The
objects are compared using the
GeometricObjectComparator
.
L
ISTING
20.5
TestComparator.java
1
import
java.util.Comparator;
2
3
public class
TestComparator {
4
public static void
main(String[] args) {
Search WWH ::
Custom Search