Java Reference
In-Depth Information
1
package java.lang;
2
3
public interface Comparable<AnyType>
4
{
5
public int compareTo( AnyType other );
6
}
figure 4.31
Comparable
interface,
Java 5 version which
is generic
instance, now implements
Comparable<String>
and has a
compareTo
method that
takes a
String
as a parameter. By making the class generic, many of the errors
that were previously only reported at runtime become compile-time errors.
4.7.2
wildcards with bounds
In Figure 4.13 we saw a static method that computes the total area in an array
of
Shapes
. Suppose we want to rewrite the method so that it works with a
parameter that is
ArrayList<Shape>
. Because of the enhanced
for
loop, the
code should be identical, and the resulting code is shown in Figure 4.32. If we
pass an
ArrayList<Shape>
, the code works. However, what happens if we pass
an
ArrayList<Square>
? The answer depends on whether an
ArrayList<Square>
IS-A
ArrayList<Shape>
. Recall from Section 4.1.10 that the technical term for
this is whether we have covariance.
In Java, as we mentioned in Section 4.1.10, arrays are covariant. So
Square[]
IS-A
Shape[]
. On the one hand, consistency would suggest that if
arrays are covariant, then collections should be covariant too. On the other
hand, as we saw in Section 4.1.10, the covariance of arrays leads to code that
compiles but then generates a runtime exception (an
ArrayStoreException
).
Because the entire reason to have generics is to generate compiler errors
rather than runtime exceptions for type mismatches, generic collections are
not covariant. As a result, we cannot pass an
ArrayList<Square>
as a parameter
to the method in Figure 4.32.
Generic collections
are not covariant.
1
public static double totalArea( ArrayList<Shape> arr )
2
{
3
double total = 0;
4
5
for( Shape s : arr )
6
if( s != null )
7
total += s.area( );
8
9
return total;
10
}
figure 4.32
totalArea
method that
does not work if
passed an
ArrayList<Square>
Search WWH ::
Custom Search