Java Reference ยท Object-Oriented Concepts
Wildcards and PECS in Java generics
Reference for Java generic wildcards: unbounded, upper-bounded and lower-bounded wildcards, the PECS rule for producers and consumers, and wildcard capture.
Generic types are invariant: List<Integer> is not a subtype of List<Number>, even though Integer is a Number. A wildcard, written ?, stands for an unknown type and lets one method accept a whole family of parameterizations. There are three forms: ? (anything), ? extends T (T or a subtype) and ? super T (T or a supertype).
The PECS rule tells you which to use: Producer Extends, Consumer Super. If a parameter only supplies values you read, use extends. If it only receives values you write, use super. If you do both, use no wildcard.
static double sum(Collection<? extends Number> source) { ... } // producer static void fill(List<? super Integer> target) { ... } // consumer
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
| Form | Meaning | Read as | Write |
|---|---|---|---|
List<?> |
List of unknown type | Object |
only null |
List<? extends T> |
List of T or a subtype | T |
only null |
List<? super T> |
List of T or a supertype | Object |
T and subtypes |
List<T> |
List of exactly T | T |
T and subtypes |
Usage notes
- PECS in the JDK:
Collections.copy(List<? super T> dest, List<? extends T> src)andComparator<? super T>insortfollow it. The signature ofStream.mapusesFunction<? super T, ? extends R>. - Return types should not use wildcards. A method returning
List<? extends Number>forces callers to deal with the wildcard. Return concrete types, accept wildcards. - Cannot add to
? extends: the compiler cannot prove which subtype the list really holds. This is the safety the rule buys you. ? super Treads asObject, because the actual element type may be any supertype.- Capture: a helper method with a named type parameter (as
swapHelper) can work with aList<?>and both read and write. - Wildcards are for method parameters and variables, not for instantiation:
new ArrayList<?>()is illegal, whilenew ArrayList<>()is fine. - Arrays versus generics: arrays are covariant (
Number[] a = new Integer[1]compiles, then fails at run time withArrayStoreExceptionon a bad store); generics are checked at compile time. - Nested wildcards like
Map<String, ? extends List<?>>are legal but hard to read; introduce a named type parameter. - Raw type vs
?:List<?>keeps type safety, rawListdoes not.