Java Reference
In-Depth Information
12.2
Comparable and Comparator
Most of the methods we wrote to handle arrays —linear search, binary search,
sorting, etc.— handle only arrays of base type int . We now show how to use an
interface to make these methods more versatile. They will massage arrays of any
base type that is a class and that has a suitable method that provides an ordering
of the instances of the class.
The new versions of these methods will not sort arrays of any primitive type
unless they are wrapped using one of the wrapper classes (see Sec. 5.1).
Interface Comparable
Interface java.util. Comparable has one method, compareTo , which is sup-
posed to provide an ordering of the objects of a class. Here is the interface:
Activity
12-3.1
/** Require method compareTo , which provides an
ordering on instances of a class */
public interface Comparable {
/** = -1 if this object < b,
0 if this object =b , and
1 if this object >b */
int compareTo(Object b);
}
Class Compares contains linear search and other methods that deal with
arrays (see Sec. 8.5). We show how to change these methods so that they work
not on an array of int s but on an array of any class whose elements are known
to be ordered (because the class implements interface Comparable ). Figure 12.4
shows class Compares with (only) one of its methods.
Activity 12-3.2
is easier to
understand!
public class Compares {
/** = position of minimum value of b */
public static int min( int [] b) { Comparable b
int p= 0;
// {inv: b[p] is the minimum of b[0..i-1]}
for ( int i= 1; i != b.length; i++) {
if (b[i] < b[p]) { b[i].compareTo(b[p])
p= i;
}
change these to these
}
return p;
}
}
Figure 12.4:
Class Compares , showing only method min working on an array of int s
Search WWH ::




Custom Search