posted 19 years ago
Thanks for the link, there's stacks of info on this site. The answer they give is -:
Why is it allowed to create an array whose component type is an unbounded wildcard parameterized type?
Because it is type-safe.
The rationale is related to the rule for other instantiations of a generic type: an unbounded wildcard parameterized type is a reifiable type and arrays of reifiable types are type-safe, in contrast to arrays of non-reifiable types, which are not safe and therefore illegal. The problem with the unreliable array store check (the reason for banning arrays with a non-reifiable component type) does not occur if the component type is reifiable.
Example (of array of unbounded wildcard parameterized type ):
Object[] pairArr = new Pair<?,?>[10] ; // fine
pairArr[0] = new Pair <Long,Long>(0L,0L); // fine
pairArr[0] = new Pair <String,String>("",""); // fine
pairArr[0] = new ArrayList <String>(); // fails with ArrayStoreException
The array store check must check whether the element added to the array is of type Pair<?,?> or of a subtype thereof. In the example the two pairs, although of different type, are perfectly acceptable array elements. And indeed, the array store check, based on the non-exact runtime type Pair , accepts the two pairs and correctly sorts out the "alien" ArrayList object as illegal by raising an ArrayStoreException . The behavior is exactly the same as for an array of the raw type, which is not at all surprising because the raw type is a reifiable type as well.