Java Generic Wildcards: Unbounded, Upper-Bounded and Lower-Bounded Types (OCP 21)
Generic wildcards for the OCP 21 exam: why List<String> isn't a List<Object>, unbounded ?, upper-bounded ? extends and lower-bounded ? super, what you can read and add through each, PECS, List<?> versus var, and the tricky declarations the exam uses.
kvi5hnuCode Sprout team member7 min readOn this page
Wildcards answer a question that type parameters can't: how do I write one method that accepts a List<Integer>, a List<Double> and a List<Number>? You'd expect plain inheritance to cover it, but it doesn't.
Generics are invariant
Integer is a subtype of Number, but List<Integer> is not a subtype of List<Number>:
List<Number> nums = new ArrayList<Integer>(); // DOES NOT COMPILE
ArrayList<Number> list = new ArrayList<Integer>(); // DOES NOT COMPILE
List<Object> objs = new ArrayList<String>(); // DOES NOT COMPILE
If it were allowed, this would break type safety:
List<Integer> ints = new ArrayList<>(List.of(7));
List<Number> nums = ints; // pretend this compiled
nums.add(2.5); // a Double now sits in a list of Integers
Integer i = ints.get(1); // ClassCastException, far away from the real mistake
Arrays work differently. They are covariant (Number[] a = new Integer[3]; compiles), so the same mistake is caught only at run time, with an ArrayStoreException. Generics catch it at compile time instead, and wildcards add back the flexibility in a safe way.
A wildcard ? stands for "some type I don't know". It appears only in uses of a generic type, such as variable, parameter and field types. It never appears in declarations of type parameters or as a direct type argument of new.

| Kind | Syntax | Example that compiles |
|---|---|---|
| unbounded | ? | List<?> a = new ArrayList<String>(); |
| upper bound | ? extends Type | List<? extends Number> b = new ArrayList<Integer>(); |
| lower bound | ? super Type | List<? super Integer> c = new ArrayList<Number>(); |
Unbounded wildcard: ?
List<?> means "a list of something". Use it when the code doesn't care about the element type:
static int countNonNull(Collection<?> items) {
int n = 0;
for (Object o : items) if (o != null) n++; // elements come out as Object
return n;
}
countNonNull(List.of("a", "b")); // fine
countNonNull(Set.of(1, 2, 3)); // fine
A parameter of type List<Object> would reject both calls (invariance), and that's the classic exam trap.
Through a List<?>:
- Reading gives
Object. - Adding anything except
nulldoesn't compile: the compiler can't know whether the list holdsStrings,Integers or something else. - Removing, clearing and other operations that don't take an element of the type still work.
List<?> is equivalent to List<? extends Object>.
List<?> vs var
List<?> a = new ArrayList<>(); // type List<?>: you can't add (except null)
var b = new ArrayList<>(); // type ArrayList<Object>: you can add anything
Both return Object from get. But b is an ArrayList<Object>, so b.add("x") and b.add(1) compile, and b can be assigned to a List<Object>. a can do neither. With nothing to infer from, the diamond falls back to Object.
Upper bound: ? extends Type
List<? extends Number> matches List<Number>, List<Integer>, List<Double> and so on: Number or any subtype. The keyword is extends even when the bound is an interface. ? implements Flyer doesn't compile.
static double total(List<? extends Number> values) {
double sum = 0;
for (Number n : values) sum += n.doubleValue(); // every element IS-A Number
return sum;
}
total(List.of(3, 4)); // List<Integer>
total(List.of(1.5, 2.5)); // List<Double>
Through a List<? extends Number>:
- Reading gives
Number, notInteger.Integer i = values.get(0)doesn't compile, because the list might holdDoubles. - Adding doesn't compile for any value except
null. You might be adding anIntegerto aList<Double>, and the compiler can't rule that out. In practice, the list is read-only for adding, althoughremove,clearandremoveIfstill work.
Erasure still applies: the compiled method takes a raw List and casts each element to Number.
Lower bound: ? super Type
List<? super Integer> matches List<Integer>, List<Number> and List<Object>: Integer or any supertype.
static void addDefaults(List<? super Integer> target) {
target.add(0); // fine: an Integer fits in a list of Integer, Number or Object
target.add(100);
}
addDefaults(new ArrayList<Integer>());
addDefaults(new ArrayList<Number>());
addDefaults(new ArrayList<Object>());
addDefaults(new ArrayList<Double>()); // DOES NOT COMPILE: Double isn't a supertype of Integer
Through a List<? super Integer>:
- Adding an
Integer, or an instance of a subtype of the bound, is allowed. - Reading gives only
Object, since the list might be aList<Object>.Integer i = target.get(0)doesn't compile.
The tricky part is that "super" describes the list's type, not the objects you add. With List<? super IOException>:
List<? super IOException> errors = new ArrayList<Exception>();
errors.add(new Exception()); // DOES NOT COMPILE: the list might be a List<IOException>
errors.add(new IOException()); // fine
errors.add(new FileNotFoundException()); // fine: a FileNotFoundException IS-A IOException
Why we need super: one method for List<String> and List<Object>
Parameter type for a method that calls list.add("hello") | Body compiles? | Accepts List<String>? | Accepts List<Object>? |
|---|---|---|---|
List<?> | no | yes | yes |
List<? extends Object> | no | yes | yes |
List<Object> | yes | no | yes |
List<? super String> | yes | yes | yes |
PECS: producer extends, consumer super
A practical way to choose:
- If the parameter produces values your code reads (a source), use
? extends T. - If it consumes values your code writes (a destination), use
? super T. - If it does both, use the exact type
T. If it does neither, use?.
The JDK follows this rule everywhere:
static <T> void copyInto(List<? super T> target, List<? extends T> source) {
for (T item : source) target.add(item);
}
// Collections.copy(List<? super T> dest, List<? extends T> src)
// List.sort(Comparator<? super E> c): a Comparator<Object> can sort a List<String>
// Collection.addAll(Collection<? extends E> c)
Comparator<? super T> is why a Comparator<Vehicle> can sort a list of Bikes.
Reading tricky declarations
With class Shape {}, class Polygon extends Shape {} and class Square extends Polygon {}:
List<?> any = new ArrayList<Shape>(); // fine: anything
List<? extends Shape> up = new ArrayList<Shape>(); // fine: Shape, Polygon or Square
List<? super Shape> down = new ArrayList<Shape>(); // fine: Shape or Object
List<? extends Polygon> p1 = new ArrayList<Shape>(); // DOES NOT COMPILE: Shape is above Polygon
List<? super Polygon> p2 = new ArrayList<Shape>(); // fine: Polygon, Shape or Object
List<?> wild = new ArrayList<? extends Shape>(); // DOES NOT COMPILE: new needs a concrete type
Method declarations:
<T> T head(List<? extends T> list) { return list.get(0); } // fine
<T> <? extends T> tail(List<? extends T> list) { ... } // DOES NOT COMPILE: a wildcard isn't a return type
<Polygon extends Shape> Polygon make(List<Polygon> list) { return new Polygon(); } // DOES NOT COMPILE: Polygon is the type parameter here
void fill(List<? super Polygon> list) { } // fine: List<Polygon>, List<Shape>, List<Object>
<X> void drain(List<X super Polygon> list) { } // DOES NOT COMPILE: only ? can use super
Rules of thumb:
- The wildcard
?appears only inside<...>of a used type. - A type parameter (
<T extends X>) can have onlyextendsbounds, neversuper.<T super X>doesn't compile. newnever takes a wildcard as a direct type argument:new ArrayList<?>()doesn't compile (a nested one, as innew ArrayList<List<?>>(), is fine).- A wildcard can't be used as a return type or a variable type by itself.
What's current
- Nothing in this article changed in Java 22 through 25, so the rules apply to both the Java 21 exam (1Z0-830) and the Java 25 exam (1Z0-831).
- Wildcard rules and the PECS idea ("producer extends, consumer super") haven't changed since Java 5.
Exam traps from this article
A complete example
The program uses Vehicle, Bike and EBike to show each wildcard in action: an unbounded counter, an upper-bounded totalWheels that reads, and a lower-bounded addDefaults that writes. A PECS copyInto combines the two, and a best method accepts a comparator for a supertype.
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
public class Solution {
static class Vehicle {
final String name;
Vehicle(String name) { this.name = name; }
int wheels() { return 4; }
@Override public String toString() { return name; }
}
static class Bike extends Vehicle {
Bike(String name) { super(name); }
@Override int wheels() { return 2; }
}
static class EBike extends Bike {
EBike(String name) { super(name); }
}
// Unbounded: any element type, read as Object
static int countNonNull(Collection<?> items) {
int n = 0;
for (Object o : items) if (o != null) n++;
return n;
}
// Upper bound: a PRODUCER of Vehicles. We can read them as Vehicle, never add
static int totalWheels(List<? extends Vehicle> fleet) {
int total = 0;
for (Vehicle v : fleet) total += v.wheels();
return total;
}
// Lower bound: a CONSUMER of Bikes. We can add Bikes (or subtypes), reads give Object
static void addDefaults(List<? super Bike> garage) {
garage.add(new Bike("city bike"));
garage.add(new EBike("cargo e-bike"));
}
// Both together: copy from a producer into a consumer
static <T> void copyInto(List<? super T> target, List<? extends T> source) {
for (T item : source) target.add(item);
}
// A bounded wildcard inside a bounded type parameter: max by any comparator of T or a supertype
static <T> T best(List<? extends T> items, Comparator<? super T> order) {
T best = items.getFirst();
for (T t : items) if (order.compare(t, best) > 0) best = t;
return best;
}
public static void main(String[] args) {
List<Vehicle> vehicles = new ArrayList<>(List.of(new Vehicle("van")));
List<Bike> bikes = new ArrayList<>(List.of(new Bike("racer")));
List<EBike> eBikes = new ArrayList<>(List.of(new EBike("commuter"), new EBike("folding")));
List<Object> things = new ArrayList<>();
// List<EBike> is NOT a List<Bike>, but it IS a List<? extends Bike>
System.out.println("non-null: " + countNonNull(eBikes) + " " + countNonNull(List.of("a", 1, 'c')));
System.out.println("wheels: vehicles " + totalWheels(vehicles) + ", bikes " + totalWheels(bikes)
+ ", e-bikes " + totalWheels(eBikes));
addDefaults(bikes); // List<Bike>
addDefaults(vehicles); // List<Vehicle>: a supertype of Bike
addDefaults(things); // List<Object>
// addDefaults(eBikes); // would not compile: an EBike list can't take a plain Bike
System.out.println("bikes " + bikes + " | vehicles " + vehicles + " | things " + things);
List<Vehicle> all = new ArrayList<>();
copyInto(all, eBikes); // T inferred: source of EBike, target of Vehicle
copyInto(all, bikes);
System.out.println("copied: " + all);
Comparator<Vehicle> byNameLength = Comparator.comparingInt(v -> v.name.length());
EBike longest = best(eBikes, byNameLength); // a Comparator<Vehicle> sorts EBikes
System.out.println("longest e-bike name: " + longest);
List<? extends Number> readOnlyView = List.of(3, 4.5, 6L);
double sum = 0;
for (Number n : readOnlyView) sum += n.doubleValue();
System.out.println("sum of mixed numbers: " + sum);
}
}
Output:
non-null: 2 3
wheels: vehicles 4, bikes 2, e-bikes 4
bikes [racer, city bike, cargo e-bike] | vehicles [van, city bike, cargo e-bike] | things [city bike, cargo e-bike]
copied: [commuter, folding, racer, city bike, cargo e-bike]
longest e-bike name: commuter
sum of mixed numbers: 13.5
Points to notice:
totalWheelsaccepted aList<Vehicle>, aList<Bike>and aList<EBike>. A parameter of typeList<Vehicle>would have accepted only the first.addDefaultsaccepted lists ofBike,VehicleandObject, and added both aBikeand anEBike. Passing theList<EBike>is commented out because it doesn't compile.- In
copyInto(all, eBikes),Twas inferred so that theEBikesource fits aVehicletarget. best(eBikes, byNameLength)used aComparator<Vehicle>to pick anEBike, thanks toComparator<? super T>.List<? extends Number>held anInteger, aDoubleand aLong, each read as aNumber.
Common questions
When should I use a type parameter <T> and when a wildcard ??
Use a type parameter when a type must be named: to link two parameters, to link a parameter to the return type, or to use the type in the body (T item). If a type appears only once and you just need flexibility, a wildcard is simpler. static <T> void copyInto(List<? super T>, List<? extends T>) uses both.
Why can I add null to a List<? extends Number>?
null belongs to every reference type, so it fits whatever the real element type is. That's legal, but it's almost never useful.
Can a field or variable have a wildcard type?
Yes: private List<? extends Shape> shapes; is legal. Wildcards are most common on method parameters, though.
Summary
- Generic types are invariant:
List<Sub>isn't aList<Super>. List<?>accepts any list, readsObject, and can't add anything butnull.List<? extends T>accepts lists ofTor its subtypes, readsT, and can't add.List<? super T>accepts lists ofTor its supertypes, can addTvalues, and readsObject.- PECS: producers use
extendsand consumers usesuper. A wildcard can't be a direct type argument ofnew(new ArrayList<?>()), a whole type by itself, or a bound in a type parameter declaration (<T super X>). Inside a type such asList<? extends T>, it's fine anywhere, including return types.
Practice quiz
Test yourself with the generic wildcards quiz: 10 exam-style questions with explanations.
You've finished Chapter 9. Check your understanding of the whole chapter with the Chapter 9 review quiz: 20 mixed questions on the Collection API, lists, sets, queues, deques, maps, sorting, sequenced collections, generic classes and methods, and wildcards.
Previous: Java Generics: Generic Classes, Interfaces, Methods and Type Erasure (OCP 21)
Next: Java Optional: Creating, Checking and Unwrapping Optional Values (OCP 21)
Related reading
- Java Generics: Generic Classes, Interfaces, Methods and Type Erasure (OCP 21)
- Java Packages and Imports: Wildcards, Conflicts, Compiling and the Class Path (OCP 21)
- Java Reflection and Generics: Class<T>, Type Tokens and the Type Interface
- Java Generics Restrictions and Limitations: What You Can't Do with Type Parameters
- Java Generics Inheritance Rules and Wildcards: extends, super and ?

More in OCP Java 21
OCP Java 21 Mock Exam 3 (1Z0-830)
The third full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), weighted toward the hardest areas: streams, concurrency, generics, modules and I/O. 120 minutes, 68% to pass, with explanations.
OCP Java 21 Mock Exam 2 (1Z0-830)
The second full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830): new questions on every objective, with more multi-select. 120 minutes, 68% to pass, with an explanation for every answer.
OCP Java 21 Mock Exam 1 (1Z0-830)
A full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), covering every objective at exam difficulty. 120 minutes, 68% to pass, with an explanation for every answer.
Quiz: Final Review (OCP 21)
Ten exam-style questions mixing the most-tested OCP Java 21 rules from the final checklist: promotion, String immutability, overloading, initialization order, collections, streams, exceptions and switch patterns, with explanations.
Discussion
Sign in to ask a question or share what you learned.