Wildcard (Java): Difference between revisions

Content deleted Content added
m ce
Line 1:
The '''wildcard''' <code>?</code> in [[Java (programming language)|Java]] is a special [[type parameter]] that controls the type safety of the use of [[Generics in Java|generic]] (parameterized) types. It can be used in variable declarations and instantiations<!--in special circumstances, see section below)--> as well as in method definitions, but not in the definition of a generic type.<ref name="gilad2004">{{citation|title=Generics in the Java Programming Language|url= http://www.oracle.com/technetwork/java/javase/generics-tutorial-159168.pdf|author=Gilad Bracha|date=June 2004|section=4. Wildcards|accessdate=6 March 2016}}</ref><ref>{{citation|url=http://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.1.2|title=The Java Language Specification|section=8.1.2 Generic Classes and Type Parameters|publisher=Oracle|accessdate=6 March 2016}}</ref> This is a form of ''use-site'' [[variance annotation]], in contrast with the ''definition-site'' variance annotations found in [[C Sharp (programming language)|C#]] and [[Scala (programming language)|Scala]].
 
== Covariance for generic types ==
Line 43:
 
== Object Creation with Wildcard ==
 
No objects may be created with a wildcard type parameter: <code>'''new''' Generic<?>()</code> is forbidden because <code>Generic<?></code> is abstract.<ref>{{citation|title=The Java Language SpecificatiosSpecification|section=Class Instance Creation Expressions|url=http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.9|publisher=Oracle}}</ref> 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>.
Line 52 ⟶ 53:
 
== Example: Lists ==
 
In the Java Collections Framework, the class <code>List<MyClass></code> represents an ordered collection of objects of type <code>MyClass</code>.
Upper bounds are specified using <code>extends</code>:
Line 98 ⟶ 100:
 
== References ==
 
{{Reflist}}
* The Java Language Specification, Third Edition (Sun), ISBN 978-0-321-24678-3 http://java.sun.com/docs/books/jls/