It would be an advantage if we only had to write a single routine for searching an array of objects, no matter what its elements may be. All that matters is that they provide a method for comparing objects in that domain. Since the Java 2 release, java.lang provides a Comparable interface with just the single method
public interface Comparable {
public int compareTo(Object o);
}
The wrapper classes for all the primitive numeric types now implement
this interface, namely
CharacterThe compareTo method behaves in the same way as String.compareTo. It returns a negative integer, zero, or a positive integer according to whether this object is less than, equal to, or greater than the specified object o.
Byte
Short
Integer
Long
Float
Double
A generic binary search method can now be written as in Figure 7.2.
public static final boolean contains(Comparable item, Comparable[] array, int n) {
int low = 0;
int high = n - 1;
while (low <= high) {
int mid = (low + high) / 2;
int compare = item.compareTo(array[mid]);
if (compare < 0) {
high = mid - 1;
} else if (compare > 0) {
low = mid + 1;
} else {
return true;
}
}
return false;
}
|
array[0]..array[n-1]. Notice that both item and array[] are of type Comparable. The local variable compare is for efficiency,
since we only want to make the comparison once. Note that the
negative and positive integers returned by an implementation of compareTo are frequently