next up previous index
Next: Doing it yourself Up: Generic methods Previous: Generic methods   Index

The Comparable Interface

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
Character
Byte
Short
Integer
Long
Float
Double
The 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.

A generic binary search method can now be written as in Figure 7.2.

Figure 7.2: A generic binary search method.
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;
}

This generalises the previous method in one additional respect, namely the inclusion of the parameter n. This is the effective length of the array. Often one uses only an initial segment of an array. The contains method now searches for the item in 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 $-1$ and $+1$ but this is not required and should not be assumed.


next up previous index
Next: Doing it yourself Up: Generic methods Previous: Generic methods   Index
Peter Williams 2005-06-07