Java Reference
In-Depth Information
If the objects in
myArray
are all of type
Gadget
, the compiler will discover that fact without our
help.
Gadget
, however, must implement
Comparable
and have a
compareTo
method.
8.2
An improvement.
By writing
T
extends
Comparable
<
T
>
, we require that
Gadget
implement the
interface
Comparable
<
Gadget
>
. But insisting that a
Gadget
object be compared only to another
Gadget
object is more restrictive than we really need to be. What would happen if we had derived
Gadget
from
Widget
, where
Widget
implements
Comparable<Widget>
, as Figure 8-1 shows? If
gadgets and widgets are similar enough to have the same basis for comparison,
Gadget
could use
the method
compareTo
it inherits from
Widget
without defining its own. But then a call to the
method
sort
with an array of gadgets and widgets as an argument would not compile.
FIGURE 8-1
The class
Gadget
is derived from the class
Widget
, which
implements the interface
Comparable
<<interface>>
Comparable<T>
+compareTo(other: T): integer
Widget
+compareTo(other: Widget): integer
Gadget
Instead of comparing an object of
T
only with other objects of
T
, we can allow comparisons of
objects of a superclass of
T
. So instead of writing
T
extends
Comparable
<
T
>
, we write
T
extends
Comparable<?
super
T>
The
wildcard
?
represents any type, but the notation
?
super
T
means any superclass of
T
. Thus, the
header for the method
sort
would be
public static
<T
extends
Comparable<?
super
T>>
void
sort(T[] a,
int
n)
Programming Tip:
To use
Comparable
with arbitrary types, write
Comparable<?
super
T>
instead of
Comparable<T>
.