Java Reference
In-Depth Information
public static String findMax( String [ ] arr )
{
int maxIndex = 0;
for( int i = 1; i < arr.length; i++ )
if( arr[i].compareTo( arr[ maxIndex ] < 0 )
maxIndex = i;
return arr[ maxIndex ];
}
If we want the findMax code to work for both types, or even others that
happen to also have a compareTo method, then we should be able to do so, as
long as we can identify a unifying type. As it turns out, the Java language
defines the Comparable interface, that contains a single compareTo method.
Many library classes implement the interface. We can also have own own
classes implement the interface. Figure 4.28 shows the basic hierarchy. Older
versions of Java require that compareTo 's parameter be listed as type Object ;
newer versions (since Java 5) will have Comparable be a generic interface,
which we discuss in Section 4.7.
With this interface, we can simply write the findMax routine to accept an
array of Comparable . The older, pre-generic style for findMax is shown in
Figure 4.29, along with a test program.
It is important to mention a few caveats. First, only objects that imple-
ment the Comparable interface can be passed as elements of the Comparable
array. Objects that have a compareTo method but do not declare that they
implement Comparable are not Comparable , and do not have the requisite IS-A
relationship.
Second, if a Comparable array were to have two objects that are incompati-
ble (e.g., a Date and a BigInteger ), the compareTo method would throw a
ClassCastException . This is the expected (indeed, required) behavior.
Third, as before, primitives cannot be passed as Comparable s, but the wrap-
pers work because they implement the Comparable interface.
figure 4.28
Three classes that
all implement the
Comparable
interface
Comparable
String
Date
BigInteger
Search WWH ::




Custom Search