Wildcard (Java): Difference between revisions

Content deleted Content added
MOS:HEAD
Line 13:
<source lang="java5">
class Generic <T extends UpperBound> {
private T t;
void write(T t) {
this.t = t;
}
}
T read() {
return t;
}
}
}
...
Line 30:
</source>
 
== Bounded Wildcardswildcards ==
 
A bounded wildcard is one with either an upper or a lower [[Inheritance (object-oriented programming)|inheritance]] constraint. The bounds can be both class and interface types. Upper bounds are expressed using the '''extends''' keyword and lower bounds using the '''super''' keyword. An upper bound on a wildcard must be a subtype of the upper bound on the type parameter it is assigned.
Line 42:
can hold instantiations of <code>Generic</code> with any type that is both a subtype of <code>UpperBound</code> and a supertype of <code>SubtypeOfUpperBound</code>. The type bounds are trivial examples that conform.
 
== Object Creationcreation with Wildcardwildcard ==
 
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 Specification|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.
Line 52:
For both cases, using no parameters is another option. This will generate a warning since it is less type-safe (see [[Raw type]]).
 
== Example: Listslists ==
 
In the Java Collections Framework, the class <code>List<MyClass></code> represents an ordered collection of objects of type <code>MyClass</code>.
Line 59:
<source lang="java5">
public void doSomething(List<? extends MyClass> list) {
for (MyClass object : list) { // OK
// do something
}
}
</source>
Line 67:
<source lang="java5">
public void doSomething(List<? extends MyClass> list) {
MyClass m = new MyClass();
list.add(m); // Compile error
}
</source>
Line 76:
<source lang="java5">
public void doSomething(List<? super MyClass> list) {
MyClass m = new MyClass();
list.add(m); // OK
}
</source>
Line 83:
<source lang="java5">
public void doSomething(List<? super MyClass> list) {
for (MyClass object : list) { // Compile error
// do something
}
}
</source>