Java Reference
In-Depth Information
we have gained quite a lot. Now, method min of class Compares can be used on
arrays of Pixels . For example, suppose we have an array b of base type Pixel
and that Pixel s have been placed in it:
Pixel[] b= new Pixel[1000];
Activity 12-3.3
executes a call
to min , show-
ing how cast-
ing works in a
way we cannot
describe on
paper.
Then we find its minimum by calling method min :
Compares.min(b)
Automatically, method compareTo , which is in each element of array b , will be
used in comparing array elements.
Implementing Comparable in other classes
Interface Comparable has been floating around the world for several years,
but it was not officially in a Java API package until version 1.2. Some classes that
do not implement Comparable can be subclassed to implement it. For example,
Fig. 12.6 defines a subclass of class java.util.Date . Methods before and
equals belong to Date . After defining MyDate , just use it in place of Date .
Classes like String and the wrapper classes (e.g. Integer ) cannot be sub-
classed, so in Java 1.1 and earlier, to get the effect of implementing Comparable
on them, you have to write an awkward-to-use class that wraps an int and imple-
ments Comparable . This class should have the necessary getter-setter methods,
perhaps returning the value not only as an int but also as an Integer . Fortu-
nately, interface Comparable was added in Java 1.2 so these sorts of shenanigans
are not necessary any more.
Interface Comparator
Interface Comparator , in package java.util , provides other methods for
comparing elements, one of which is an equality test:
import java.util.date;
public class MyDate extends Date implements Comparable {
/** = 0 if this Date < ob ;
1 if this Date = ob ;
-1 if this Date > ob */
public int compareTo(Object ob) {
if ( this .before((Date)ob))
{ return -1; }
if ( this .equals((Date)ob))
{ return 0; }
return 1;
}
}
Figure 12.6:
Class MyDate , which extends java.util.Date
Search WWH ::




Custom Search