Java Reference
In-Depth Information
Generic interfaces
enable you to specify, with a single interface declaration, a set of related
types.
Comparable<T>
objects have a
compareTo
method
. For example, if we have two
In-
teger
objects,
integer1
and
integer2
, they can be compared with the expression:
integer1.compareTo(integer2)
When you declare a class that implements
Comparable<T>
, you must implement method
compareTo
such that it compares the contents of two objects of that class and returns the
comparison results
.
As specified in interface
Comparable<T>
's documentation,
compareTo
must
return
0
if the objects are equal, a negative integer if
object1
is less than
object2
or
a positive integer if
object1
is greater than
object2
. For example, class
Integer
's
compa-
reTo
method compares the
int
values stored in two
Integer
objects. A benefit of imple-
menting interface
Comparable<T>
is that
Comparable<T>
objects can be used with the
sorting and searching methods of class
Collections
(package
java.util
). We discussed
those methods in Chapter 16. In this example, we'll use method
compareTo
in method
maximum
to help determine the largest value.
1
// Fig. 20.5: MaximumTest.java
2
// Generic method maximum returns the largest of three objects.
3
4
public class
MaximumTest
5
{
6
public static void
main(String[] args)
7
{
8
System.out.printf(
"Maximum of %d, %d and %d is %d%n%n"
,
3
,
4
,
5
,
9
maximum(
3
,
4
,
5
));
10
System.out.printf(
"Maximum of %.1f, %.1f and %.1f is %.1f%n%n"
,
11
6.6
,
8.8
,
7.7
, maximum(
6.6
,
8.8
,
7.7
));
12
System.out.printf(
"Maximum of %s, %s and %s is %s%n"
,
"pear"
,
13
"apple"
,
"orange"
, maximum(
"pear"
,
"apple"
,
"orange"
));
14
}
15
16
// determines the largest of three Comparable objects
public static
<T
extends
Comparable<T>> T maximum(T x, T y, T z)
{
T max = x;
// assume x is initially the largest
if
(y.compareTo(max) >
0
)
max = y;
// y is the largest so far
if
(z.compareTo(max) >
0
)
max = z;
// z is the largest
return
max;
// returns the largest object
}
17
18
19
20
21
22
23
24
25
26
27
28
29
}
// end class MaximumTest
Maximum of 3, 4 and 5 is 5
Maximum of 6.6, 8.8 and 7.7 is 8.8
Maximum of pear, apple and orange is pear
Fig. 20.5
|
Generic method
maximum
with an upper bound on its type parameter.