Java Reference
In-Depth Information
lsCopy);
copiesa
List
of
String
toanother
List
of
String
.Similarly,itde-
termines that
copyList(lc, lcCopy);
copies a
List
of
Circle
to another
List
of
Circle
.
When you run this application, it generates the following output:
A
B
C
A
B
C
(10.0, 20.0, 30.0)
(5.0, 4.0, 16.0)
(10.0, 20.0, 30.0)
(5.0, 4.0, 16.0)
Arrays and Generics
plainwhyIspecified
elements = (E[]) new Object[size];
insteadofthe
morecompact
elements = new E[size];
expression.BecauseofJava'sgenerics
implementation,itisn'tpossibletospecifyarray-creationexpressionsthatinvolvetype
parameters (e.g.,
new E[size]
or
new List<E>[50]
) or actual type arguments
(e.g.,
new Queue<String>[15]
).Ifyouattempttodoso,thecompilerwillreport
a
generic array creation
error message.
Before I present an example that demonstrates why allowing array-creation expres-
sions that involve type parameters or actual type arguments is dangerous, you need to
understandreification andcovariance inthecontextofarrays,anderasure,whichisat
the heart of how generics are implemented.
Reification
is representing the abstract as if it was concrete —for example, making
amemoryaddressavailablefordirectmanipulationbyotherlanguageconstructs.Java
arrays are reified in that they're aware of their element types (an element type is
storedinternally)andcanenforcethesetypesatruntime.Attemptingtostoreaninvalid
element in an array causes the JVM to throw an instance of the
java.lang.ArrayStoreException
class.