Java Reference
In-Depth Information
Display 13.5
Sorting Method for Array of
Comparable
(part 2 of 2)
40
/**
41
Precondition: i and j are legal indices for the array a.
42
Postcondition: Values of a[i] and a[j] have been interchanged.
43
*/
44
private static void
interchange(
int
i,
int
j, Comparable[] a)
45 {
46 Comparable temp;
47 temp = a[i];
48 a[i] = a[j];
49 a[j] = temp;
//original value of a[i]
50 }
51 }
EXAMPLE:
(continued)
Display 13.6 shows a demonstration of using the sorting method given in Display 13.5. To
understand why the demonstration works, you need to be aware of the fact that both of
the classes
Double
and
String
implement the
Comparable
interface.
If you were to check the full documentation for the class
Double
, you would see
that
Double
implements the
Comparable
interface and so has a
compareTo
method.
Moreover, for objects
o1
and
o2
of
Double
,
o1.compareTo(o2) < 0
//o1 "comes before" o2
means the same thing as
o1.doubleValue() < o2.doubleValue()
So, the implementation of the
Comparable
interface for the class
Double
is really
just the ordinary less-than relationship on the
double
values corresponding to the
Double
objects.
Similarly, if you were to check the full documentation for the class
String
,
you would see that
String
implements the
Comparable
interface and so has a
compareTo
method. Moreover, the implementation of the
compareTo
method for
the class
String
is really just the ordinary lexicographic relationship on the strings.
This Programming Example uses the standard library classes
Double
and
String
for the base type of the array. You can do the same thing with arrays whose base
class is a class you defined, so long as the class implements the
Comparable
interface
(including the standard semantics, which we discussed earlier in the Pitfall “Interface
Semantics Are Not Enforced”).
This Programming Example does point out one restriction on interfaces. They can
apply only to classes. A primitive type cannot implement an interface. So, in Display 13.6,
we could not sort an array with base type
double
using the sorting method for an array of
Comparable
. We had to settle for sorting an array with base type
Double
. This is a good
example of using a wrapper class with its “wrapper class personality.”