Java Reference
In-Depth Information
ences). In this case, an array of
Point
references is a supertype of an array of
Co-
loredPoint
references.Theonarrayanalogyisthatasubtypeisalsoasupertype.For
example, a
Throwable
instance is a kind of
Object
instance.
Covarianceisdangerouswhenabused.Forexample,thethirdline(
ptArray[0] =
new Point();
)resultsin
ArrayStoreException
atruntimebecausea
Point
instanceisnota
ColoredPoint
instance.Withoutthisexception,anattempttoaccess
the nonexistent member
color
crashes the JVM.
Unlikewitharrays,agenerictype'stypeparametersarenotreified.They'renotavail-
able at runtime because they're thrown away after the source code is compiled. This
“throwingawayoftypeparameters”isaresultof
erasure
,whichalsoinvolvesinserting
caststoappropriatetypeswhenthecodeisn'ttypecorrect,andreplacingtypeparamet-
ers by their upper bounds (such as
Object
).
Note
The compiler performs erasure to let generic code interoperate with legacy
(nongeneric) code. It transforms generic source code into nongeneric runtime code.
One consequence of erasure is that you cannot use the
instanceof
operator with
parameterized types apart from unbounded wildcard types. For example, it's illegal
to specify
List<Employee> le = null; if (le instanceof Ar-
rayList<Employee>) {}
. Instead, you must change the
instanceof
expres-
sion to
le instanceof ArrayList<?>
(unbounded wildcard) or
le in-
stanceof ArrayList
(raw type, which is the preferred use).
Suppose you could specify an array-creation expression involving a type parameter
or an actual type argument. Why would this be bad? For an answer, consider the fol-
lowing example, which should generate an
ArrayStoreException
instead of a
ClassCastException
but doesn't do so:
List<Employee>[] empListArray = new List<Employee>[1];
List<String> strList = new ArrayList<>();
strList.add("string");
Object[] objArray = empListArray;
objArray[0] = strList;
Employee e = empListArray[0].get(0);
Let'sassumethatthefirstline,whichcreatesaone-elementarraywherethiselement
storesa
List
of
Employee
,islegal.Thesecondlinecreatesa
List
of
String
,and
the third line stores a single
String
object in this list.