Reading Bounded Wildcards
Wildcards: List<? extends Number> is a list of an unknown subtype of Number (Producer). You can read it as Number, but you cannot write to it arbitrarily (except for null).
List<? super Integer> is a Consumer: you can write Integer to it, but reading will yield Object.
Mnemonic PECS: producer extends, consumer super.
Example: sum(List<? extends Number>) adds numbers from lists of Integer or Double.
$$\mathtt{List\lt ?\ super\ Integer\gt }$$
| Wildcard | add(Integer) |
|---|---|
| List<? super Integer> | type-safe |
| List<? extends Integer> | rejected by the compiler |
| ## Where used |
PECS in library methods (addAll, Producer/Consumer of Collections). Framework code (Spring, Guava-like) is full of ? extends / ? super; reading the signature determines whether insertion or only reading is allowed.
Depth
An upper wildcard bound describes a source of an unknown but sufficiently specific type. Values can be safely read as the supertype, but writing is not possible except for null, because the concrete subtype remains unknown.
A lower bound, on the other hand, describes a target that can accept values of a specific type. When reading, only Object is safe. This asymmetry is often summarized as producer extends, consumer super.
Wildcards express relationships between calls without binding a type name multiple times. When input and output must share the same unknown type, a named method type parameter is usually more precise.
Difficulty levels
- Determine safe read and write operations.
- Choose upper and lower bounds based on data flow.
- Distinguish between wildcard and named method type parameter.
Pitfalls
The bound does not specify the exact element type. Therefore, with ? extends Number, you are not allowed to insert any arbitrary Number.
Tasks
Card Info
- Topic: Algorithms and Data Structures
- Difficulty: Intermediate
- Completed: 0 users