Wildcards in Java Generics
Learn Java wildcard bounds: read with ? extends T, write with ? super T, and use PECS as a guide for flexible, type-safe generic methods.
Learn Java wildcard bounds: read with ? extends T, write with ? super T, and use PECS as a guide for flexible, type-safe generic methods.
Wildcards in Java Generics
Wildcards (?) let a method work with a generic type argument it does not need to name. An upper bound (? extends T) supports read-oriented code; a lower bound (? super T) accepts values of type T; and an unbounded wildcard (?) works when the element type does not matter. PECS (Producer Extends, Consumer Super) is a useful design heuristic, not a rule for every generic signature.
When to Use Wildcards
- Read-oriented parameters — use
? extends Twhen a method reads values asT; the type system still permits addingnull - Write-oriented parameters — use
? super Twhen a method adds values of typeT; values read from it have typeObject - Flexible APIs — when a method works with any subtype or supertype of a known type
- Copying between collections — use
? extends Tfor the source and? super Tfor the destination (PECS)
When NOT to Use Wildcards
- Return types — a wildcard can make callers reason about an unknown type; prefer a concrete type or type parameter when that gives a clearer API
- Class fields — use a wildcard only when the unknown element type is intentional; use a type parameter when the class needs to preserve a specific relationship
- Overly complex signatures — chained wildcards like
List<? extends List<? extends Number>>are hard to read and usually a sign of over-engineering
Code Example: Upper-Bounded Wildcard (? extends T)
// Reading: we only need to know elements are at least T
public static double sum(List<? extends Number> numbers) {
double total = 0.0;
for (Number n : numbers) { // safe read — Number is the upper bound
total += n.doubleValue();
}
return total;
}
// Works with any List of a Number subtype
List<Integer> ints = Arrays.asList(1, 2, 3);
List<Double> doubles = Arrays.asList(1.1, 2.2);
sum(ints); // ? extends Number matches Integer
sum(doubles); // ? extends Number matches Double
Code Example: Lower-Bounded Wildcard (? super T)
// Writing: we can accept T or any supertype of T
public static void addNumbers(List<? super Integer> list) {
list.add(1); // safe write — we know list holds at least Integer
list.add(2);
// list.add(1.5); // compile error — list might be List<Number>
}
List<Number> numList = new ArrayList<>();
List<Object> objList = new ArrayList<>();
addNumbers(numList); // ? super Integer matches Number
addNumbers(objList); // ? super Integer matches Object
Code Example: PECS (Producer Extends, Consumer Super)
public static <T> void copy(List<? extends T> source, List<? super T> dest) {
for (T item : source) { // source produces T (we read it)
dest.add(item); // dest consumes T (we write to it)
}
}
List<Number> numbers = new ArrayList<>();
List<Integer> ints = Arrays.asList(1, 2, 3);
copy(ints, numbers); // T = Number, source=? extends Integer, dest=? super Number
Code Example: Unbounded Wildcard (?)
public static boolean isEmpty(List<?> list) {
return list.isEmpty();
// we only call methods common to all List<?> regardless of element type
}
// List<?> means "a List of some unknown type"
// We can read elements as Object (everything is an Object)
public static void printAll(List<?> list) {
for (Object item : list) {
System.out.println(item);
}
// list.add("new"); // compile error — the element type is unknown
list.add(null); // permitted by the type system
}
Mermaid Diagram: Wildcard Variance
classDiagram
direction TB
class Number
class Integer
class Double
class Object
Integer --|> Number
Double --|> Number
Number --|> Object
Failure Scenarios
1. Adding to ? extends T
List<? extends Number> may refer to a List<Integer>, a List<Double>, or another list of a Number subtype. The compiler cannot tell which one, so it rejects adding a non-null Number: the list might be a List<Integer>.
public static void wrongAdd(List<? extends Number> list) {
// list.add(Double.valueOf(1.0)); // compile-time error
list.add(null); // type-safe, though this list implementation may reject null
}
The wildcard is read-oriented, not strictly read-only. Java also permits operations such as adding null, clearing the list, or removing an element. The collection itself may reject those operations, for example if it is unmodifiable or does not allow nulls.
2. Reading From ? super T
? super Integer may refer to a List<Integer>, List<Number>, or List<Object>. It can accept an Integer, but a value read from it is only guaranteed to be an Object.
public static void wrongRead(List<? super Integer> list) {
// Integer value = list.get(0); // compile-time error
Object value = list.get(0); // only Object is guaranteed
}
That is why ? super T is useful for a destination: it can accept T, while reads remain safe as Object. Do not cast a read to T unless you have an independent guarantee about the stored values.
3. Mixing Read and Write with the Same Wildcard
The wildcard bounds support different operations. ? extends T lets you read as T, but not add an arbitrary T; ? super T accepts T, but only promises Object when you read. If one method needs to read and write the same list, give both operations the same type parameter.
public static void mixed(List<? extends Number> list) {
list.add(Integer.valueOf(1)); // compile error
Number n = list.get(0); // fine
}
// ? extends T is read-oriented; ? super T is write-oriented.
This Java 7+ example uses the diamond operator. The wildcard parameter accepts the value, while the type parameter preserves its type in the return value:
public static <T> T appendAndReturn(List<? super T> destination, T value) {
destination.add(value);
return value;
}
List<Object> destination = new ArrayList<>();
Integer saved = appendAndReturn(destination, 42); // T is Integer
System.out.println(saved);
Output: 42.
The destination can store Integer because its element type is Object, and the method still returns an Integer. It returns the argument, not a value read from destination; a read from List<? super T> is only guaranteed to be Object. For operations that need to read and write the same list as T, use List<T> so both types match.
Trade-Off Table
| Pattern | Use When | Cannot Do |
|---|---|---|
? extends T |
Reading elements as T |
Add non-null elements of an unknown subtype |
? super T |
Writing elements of type T |
Read as anything more specific than Object |
? (unbounded) |
Operations that do not depend on element type | Read as anything more specific than Object / add non-null values |
<T> (parameter) |
Needing both read and write, or return type | More verbose call site |
Observability Checklist
- Confirm wildcard direction matches the data flow (PECS rule)
- Check return types — prefer a concrete type or type parameter when it gives callers a clearer contract
- Verify static analysis flags “Exceeds bounds of wildcard” warnings
- Ensure API documentation describes the operations each wildcard permits
- Consider refactoring to
<T>if a method signature has multiple wildcards that confuse callers
Security Notes
-
Wildcards do not enforce element types at runtime: ordinary JVM descriptors use
Listfor bothList<? extends Number>andList<Integer>. A class file may retain the generic declaration for reflection, but the JVM does not check collection elements against it. Validate untrusted data at the boundary. -
Raw types bypass compile-time checks: a
List<?>reference does not let you add an incompatible value. A raw alias can bypass the generic check, though, and a later typed read may throwClassCastException:List<String> strings = new ArrayList<>(); List raw = strings; raw.add(42); // unchecked warning String value = strings.get(0); // ClassCastException -
Reflection and wildcards:
Method.getParameterTypes()returns erasedClassvalues;getGenericParameterTypes()can expose declared wildcards from the class-file signature. Reflection does not make the JVM enforce those declarations.
Pitfalls
-
?vsObjectin Lists:List<?>andList<Object>are not the same.List<?>has an unknown element type, so you cannot add a non-null value;List<Object>accepts any object. -
Capture confusion: When a wildcard is captured by inference, you may get compiler messages like “capture#1 of ?” — this happens when the compiler infers a specific type for the wildcard but cannot express it.
-
No nested wildcards for collections:
List<List<? extends Number>>is valid but hard to use — you can read inner lists but not add elements to them.
Quick Recap
? extends T— producer pattern: read elements asT; the type system permits addingnull, but not an arbitrary non-null value? super T— consumer pattern: write elements asT, read asObject?(unbounded) — unknown type; read asObjectand add onlynull- PECS is a heuristic: use
extendsfor values the method reads from a parameter, andsuperfor values it writes to one - Wildcards provide call-site flexibility. Return types and fields can use them, but a concrete type or type parameter may give a clearer API
- The JVM does not enforce generic arguments at runtime; class files may retain them in generic signature metadata
Key Takeaways
Java generics are invariant: List<Integer> is not a subtype of List<Number>. A method that accepts List<? extends Number> can still read both integer and double lists as Number, while keeping the compiler’s type checks.
PECS (Producer Extends, Consumer Super) is a useful heuristic. Use ? extends T when a parameter produces values the method reads as T; use ? super T when the method writes values of type T into it. These bounds guide the compiler, but they do not make a collection immutable or prevent it from rejecting an operation for its own reasons.
Wildcards are most useful for making method parameters flexible. A wildcard field or return type is legal, but it can leave callers with an unknown element type; use one when that is the intended contract, otherwise prefer a concrete type or a named type parameter.
The bounded wildcard ? extends T lets you read as T, while blocking arbitrary non-null writes because the concrete element type is unknown. ? super T lets you write as T, but reads are only guaranteed to be Object. Those limits are what let the same method accept multiple related generic types safely.
For how this works under the hood, see Type Erasure in Java Generics. The JVM does not enforce wildcard bounds, though a class file may retain the declaration in its generic signature.
Interview Questions
List<Object> and List<?>?List<Object> accepts any type — you can add String, Integer, anything. List<?> (unbounded wildcard) accepts null but nothing else, because the wildcard represents an unknown type and the compiler refuses to add anything it cannot guarantee is of that unknown type. List<Object> is concrete; List<?> is deliberately restrictive.Further Reading
- Generic Classes — classes with type parameters
- Generic Methods — writing flexible methods with type parameters
- Type Erasure — how generics are erased at compile time
- Type Bounds — upper and lower bounds on type parameters
- Java Collections Utility — utility methods that use wildcards
- Oracle: Guidelines for Wildcard Use — official guidance on choosing bounds
Conclusion
Wildcards (?) let generic methods accept related type arguments while retaining compile-time checks. ? extends T supports reads as T and permits null, but not arbitrary non-null writes. ? super T accepts values of type T and guarantees reads only as Object. PECS is a useful heuristic for choosing between them.
The JVM does not enforce generic arguments at runtime, though class files may retain wildcard declarations in signature metadata. Wildcards are legal in fields and return types, but a concrete type or named type parameter can be easier for callers to use. See Type Erasure in Java Generics for the distinction between erased runtime descriptors and retained signatures.
Category
Related Posts
Abstract Classes in Java: Interfaces and Composition
Compare Java interfaces, abstract classes, and composition, then see when shared state, default methods, or sealed types change the design choice.
Arithmetic Operators in Java: Division, Overflow, Promotion
Compare Java arithmetic with runnable examples of division, negative remainders, overflow, type promotion, and BigDecimal for decimal money.
Java Array Basics: Length, Bounds, Copies, and Resizing
Learn Java arrays through runtime-sized allocation, bounds checks, aliasing, copying, and the fixed length that distinguishes them from ArrayList.