We can't instantiate an unbounded object ie List<String> myList1 = (List<String>) new List<?>(); // Compile error so how come we can instantiate an array of unbounded objects ie List<String> myList2 = (List<String>) new List<?>; // Ok [ October 07, 2005: Message edited by: Barry Gaunt ]
are you sure that code compiles without an error? I'm not sure u can use List<String> //this
anyway, you will find heaps of details about why you cannot and other gimmicky stuff at http://angelikalanger.camelot.de at the generics FAQ section, read it and convince yourself
"It's not enough that we do our best; sometimes we have to do<br />what's required."<br /> <br />-- Sir Winston Churchill
Joined: Jul 14, 2005
Akshay List<String> myList2 = (List<String>) new List<?>; compiles ok in Eclipse SDK 3.1. Why do you say it's not ok? Regards DS
Joined: Aug 18, 2005
Originally posted by david scollan: Akshay List<String> myList2 = (List<String>) new List<?>; compiles ok in Eclipse SDK 3.1. Why do you say it's not ok? Regards DS
I'm sorry, the previous link was supposed to be http://www.langer.camelot.de/GenericsFAQ/JavaGenericsFAQ.html that. Anyway, the code compiles, I mean, it throws unchecked warnings. And if you're using generics, then your prime concern is to get the code compiled without any warnings regarding generic usage.
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<?,?> ; // fine pairArr = new Pair <Long,Long>(0L,0L); // fine pairArr = new Pair <String,String>("",""); // fine pairArr = 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.