Arrays of Parameterized Types
There is one place where we haven’t yet considered how generic types affect the Java language: array types. After everything we’ve seen, it would seem natural to expect that arrays of generic types would come along for the ride. But as we’ll see, Java has a schizophrenic relationship with arrays of parameterized types.
The first thing we need to do is recall how arrays work for regular
Java types. An array is a kind of built-in collection of some base type of
element. Furthermore, array types (including all multidimensional
variations of the array) are true types in the Java language and are
represented at runtime by unique class types. This is where the trouble
begins. Although arrays in Java act a lot like generic collections (they
change their APIs to adopt a particular type for “reading” and “writing”),
they do not behave like Java generics with respect to their type
relationships. As we saw in Chapter 6, arrays
exist in the Java class hierarchy stemming from Object and extending down parallel branches with
the plain Java objects.
Arrays are covariant subtypes of other
types of arrays, which means that, unlike concrete generic types, although
they change their method signatures, they are still related to their
parents. This means that Strings [] in
Java is a subtype of Object []. This
brings up the aliasing problem that we mentioned earlier. An array of
Strings can be aliased as an array of
Objects and we can attempt to put things into it illegally ...