Java Reference
In-Depth Information
we know is that Square implements Comparable<Shape> . Thus, a Square IS-A
Comparable<Shape> , but it IS-NOT-A Comparable<Square> !
As a result, what we need to say is that AnyType IS-A Comparable<T> where
T is a superclass of AnyType . Since we do not need to know the exact type T , we
can use a wildcard. The resulting signature is
public static <AnyType extends Comparable<? super AnyType>>
Figure 4.36 shows the implementation of findMax . The compiler will
accept arrays of types T only such that T implements the Comparable<S> inter-
face, where T IS-A S . Certainly the bounds declaration looks like a mess. For-
tunately, we won't see anything more complicated than this idiom.
4.7.5 type erasure
Generic types, for the most part, are constructs in the Java language but not in
the Virtual Machine. Generic classes are converted by the compiler to non-
generic classes by a process known as type erasure . The simplified version of
what happens is that the compiler generates a raw class with the same name
as the generic class with the type parameters removed. The type variables are
replaced with their bounds, and when calls are made to generic methods that
have an erased return type, casts are inserted automatically. If a generic class
is used without a type parameter, the raw class is used.
Generic classes are
converted by the
compiler to non-
generic classes by
a process known as
type erasure .
One important consequence of type erasure is that the generated code is
not much different than the code that programmers have been writing before
generics and in fact is not any faster. The significant benefit is that the pro-
grammer does not have to place casts in the code, and the compiler will do
significant type checking.
Generics do not
make the code
faster. They do
make the code
more type-safe at
compile time.
4.7.6 restrictions on generics
There are numerous restrictions on generic types. Every one of the restrictions
listed here is required because of type erasure.
figure 4.36
Generic static method
to find largest element
in an array. Illustrates
a bounds on the type
parameter
1 public static <AnyType extends Comparable<? super AnyType>>
2 AnyType findMax( AnyType [ ] a )
3 {
4 int maxIndex = 0;
5
6 for( int i = 1; i < a.length; i++ )
7 if( a[ i ].compareTo( a[ maxIndex ] ) > 0 )
8 maxIndex = i;
9
10 return a[ maxIndex ];
11 }
 
Search WWH ::




Custom Search