Java Reference
In-Depth Information
primitive types
Primitive types cannot be used for a type parameter. Thus
ArrayList<int>
is
illegal. You must use wrapper classes.
Primitive types can-
not be used for a
type parameter.
instanceof
tests
instanceof
tests and type casts work only with the raw type. Thus, if
instanceof
tests
and type casts
work only with the
raw type.
ArrayList<Integer> list1 = new ArrayList<Integer>( );
list1.add( 4 );
Object list = list1;
ArrayList<String> list2 = (ArrayList<String>) list;
String s = list2.get( 0 );
was legal. then at runtime the typecast would succeed since all types are
ArrayList
. Eventually, a runtime error would result at the last line because the
call to
get
would try to return a
String
but could not.
static contexts
In a generic class, static methods and fields cannot refer to the class's type
variables since after erasure, there are no type variables. Further, since there is
really only one raw class, static fields are shared among the class's generic
instantiations.
Static methods and
fields cannot refer
to the class's type
variables. Static
fields are shared
among the
class's generic
instantiations.
instantiation of generic types
It is illegal to create an instance of a generic type. If
T
is a type variable, the
statement
T obj = new T( ); // Right-hand side is illegal
is illegal.
T
is replaced by its bounds, which could be
Object
(or even an
abstract class), so the call to
new
cannot make sense.
It is illegal to
create an instance
of a generic type.
generic array objects
It is illegal to create an array of a generic type. If
T
is a type variable, the statement
It is illegal to cre-
ate an array of a
generic type.
T [ ] arr = new T[ 10 ]; // Right-hand side is illegal
is illegal.
T
would be replaced by its bounds, which would probably be
Object
,
and then the cast (generated by type erasure) to
T[]
would fail because
Object[]
IS-NOT-A
T[]
. Figure 4.37 shows a generic version of
SimpleArrayL-
ist
previously seen in Figure 4.24. The only tricky part is the code at line 38.
Because we cannot create arrays of generic objects, we must create an array
of
Object
and then use a typecast. This typecast will generate a compiler warn-
ing about an unchecked type conversion. It is impossible to implement the
generic collection classes with arrays without getting this warning. If clients
want their code to compile without warnings, they should use only generic
collection types, not generic array types.
Search WWH ::
Custom Search