Java Reference
In-Depth Information
5 GeometricObject g1 =
new
Rectangle(
5
,
5
);
6 GeometricObject g2 =
new
Circle(
5
);
7
8 GeometricObject g =
9
max(g1, g2,
new
GeometricObjectComparator());
invoke
max
10
11 System.out.println(
"The area of the larger object is "
+
12 g.getArea());
13 }
14
15
public static
GeometricObject max(GeometricObject g1,
16 GeometricObject g2, Comparator<GeometricObject> c) {
17
the
max
method
if
(c.compare(g1, g2) >
0
)
invoke
compare
18
return
g1;
19
else
20
return
g2;
21 }
22 }
The area of the larger object is 78.53981633974483
The program creates a
Rectangle
and a
Circle
object in lines 5-6 (the
Rectangle
and
Circle
classes were defined in Section 13.2, Abstract Classes). They are all subclasses of
GeometricObject
. The program invokes the
max
method to obtain the geometric object
with the larger area (lines 8-9).
The
GeometricObjectComparator
is created and passed to the
max
method (line 9) and
this comparator is used in the
max
method to compare the geometric objects in line 17.
Note
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
.
Comparable
vs.
Comparator
natural order
using comparator
20.15
✓
✓
What are the differences between the
Comparable
interface and the
Comparator
interface? In which package is
Comparable
, and in which package is
Comparator
?
Check
Point
20.16
How do you define a class
A
that implements the
Comparable
interface? Are two
instances of class
A
comparable? How do you define a class
B
that implements the
Comparator
interface and override the
compare
method to compare to objects of
type
B1
? How do you invoke the
sort
method to sort a list of objects of the type
B1
?
The
Collections
class contains static methods to perform common operations in a
collection and a list.
Key
Point
Section 11.12 introduced several static methods in the
Collections
class for array lists.
The
Collections
class contains the
sort
,
binarySearch
,
reverse
,
shuffle
,
copy
, and
fill
methods for lists, and
max
,
min
,
disjoint
, and
frequency
methods for collections,
as shown in Figure 20.7.
Search WWH ::
Custom Search