Wildcard (Java): Difference between revisions

Content deleted Content added
add editor comment
Line 46:
No objects may be created with a wildcard type parameter: <code>'''new''' Generic<?>()</code> is forbidden because <code>Generic<?></code> is abstract. In practice, this is unnecessary because if one wanted to create an object that was assignable to a variable of type <code>Generic<?></code>, one could simply use any arbitrary type (that falls within the constraints of the wildcard, if any) as the type parameter.
 
However, <code>new List<Generic<?>>()</code> is allowed, because the wildcard is not a parameter to the instantiated type <code>List</code>. The same holds for <code>new List<List<?>>()</code>.
On the other hand, an array object that is an array of a parameterized type may be created only by an unconstrained (i.e. with a wildcard type parameter) type (and by no other instantiations) as the component type: <code>'''new''' Generic<?>[20]</code> is correct, while <code>'''new''' Generic<UpperBound>[20]</code> is prohibited.
 
On the other hand, anAn array object that is an array of a parameterized type may be created only by an unconstrained (i.e. with aan unbound wildcard type parameter) type (and by no other instantiations) as the component type: <code>'''new''' Generic<?>[20]</code> is correct, while <code>'''new''' Generic<UpperBoundSomeType>[20]</code> is prohibitednot.
An example of using a wildcard in List's instantiation is contained in the article [[Generics in Java]].
 
== Example: Lists ==