Summary
Wildcards allow the bounding of the type parameters.
Upper-Bounded Wildcards
Upper-bounded wildcards are covariant.
This means that if A<? extends S>
A<? extends T>
.
Similarly, for any type A<S>
A<? extends S>
Lower-Bounded Wildcards
Lower-bounded wildcards are contravariant.
This means that if A<? super T>
A<? super S>
.
Similarly, for any type A<S>
A<? super S>
Unbounded Wildcards
The complex type A<?>
is the supertype of all possible A<T>
.
Differences between:
A<?>
: Complex type of some specific but unknown typeA<Object>
: Complex type ofObject
instances with type checkingA
: Complex type ofObject
instances without type checking.
PECS
Producer Extends, Consumer Super
- If the variable is a producer (it returns a variable of type
) it should be declared <? extends T>
. - If the variable is a consumer (it accepts a variable of type
) it should be declared <? super T>
.