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.

published: reading time: 18 min read author: Geek Workbench updated: November 20, 2026
Quick Summary

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 T when a method reads values as T; the type system still permits adding null
  • Write-oriented parameters — use ? super T when a method adds values of type T; values read from it have type Object
  • Flexible APIs — when a method works with any subtype or supertype of a known type
  • Copying between collections — use ? extends T for the source and ? super T for 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 List for both List<? extends Number> and List<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 throw ClassCastException:

    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 erased Class values; getGenericParameterTypes() can expose declared wildcards from the class-file signature. Reflection does not make the JVM enforce those declarations.

Pitfalls

  1. ? vs Object in Lists: List<?> and List<Object> are not the same. List<?> has an unknown element type, so you cannot add a non-null value; List<Object> accepts any object.

  2. 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.

  3. 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 as T; the type system permits adding null, but not an arbitrary non-null value
  • ? super T — consumer pattern: write elements as T, read as Object
  • ? (unbounded) — unknown type; read as Object and add only null
  • PECS is a heuristic: use extends for values the method reads from a parameter, and super for 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

1. What is the difference between ? extends T and ? super T in Java generics?
? extends T represents an unknown subtype of T. You can read elements as T, but cannot add an arbitrary non-null T; the actual list might have a more specific element type. ? super T represents an unknown supertype of T. You can add values of type T, while reads are only guaranteed to be Object. The type system also permits adding null to either reference-typed list.
2. What does PECS stand for and when should you use each wildcard?
PECS stands for **Producer Extends, Consumer Super**. It is a useful heuristic: use ? extends T for a source the method reads from, and ? super T for a destination it writes to. If the method reads and writes the same collection, use a type parameter such as List<T> so both operations share the same element type.
3. Why cannot you add elements to a List<? extends Number>?
List<? extends Number> could be a List<Integer> or a List<Double>, so the compiler rejects adding an arbitrary non-null Number. It does permit null, although the collection may reject null at runtime.
4. What is the difference between 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.
5. Can wildcards be used in class declarations?
No. Wildcards are only for usage sites — method parameters, local variable types, return types. A class must declare a type parameter (e.g., class Box<T>), not a wildcard. You can use wildcards when instantiating or when a method accepts a wildcard argument, but the class definition itself uses <T>.
6. What is the difference between List<T> and List<? extends T>?
List<T> is invariant — List<String> is not a subtype of List<Object>. List<? extends T> is covariant — you can pass a List<String> where List<? extends Object> is expected. However, the wildcard restricts write operations: you cannot add non-null elements to ? extends T because the compiler does not know the concrete type. List<T> allows both reads and writes with full type safety at the call site."
7. How do wildcards behave with nested generic types like List<List<? extends Number>>?
This type is valid. You can read each inner list as List<? extends Number>, but cannot add an arbitrary non-null Number to it because its element subtype is unknown. If the code becomes hard to follow, introduce a named type or simplify the API.
8. What does capture conversion mean in the context of wildcards?
It means the compiler has inferred a specific type for the wildcard at a call site but cannot express that type in source code. This happens in inference chains where the compiler captures the wildcard's inferred type internally for type checking but the type cannot be written back as an explicit type argument. It is an internal compiler artifact — you usually see it when combining generics with method overloads or complex inference scenarios."
9. Can a class declaration use a wildcard as its type parameter?
No. A class declaration must use a type parameter (class Box<T>), not a wildcard. Wildcards are only for usage sites — method parameters, local variable declarations, and return types. You cannot write class Box<?> or class Box<? extends Number>. You can, however, use a wildcard when instantiating: Box<? extends Number> as a type for a local variable, though this has limited use."
10. How do wildcards interact with Java arrays?
Arrays in Java are covariant — String[] is a subtype of Object[]. Wildcards and arrays interact differently: a List<? extends Number> is not directly representable as an array (you cannot create Number[] from List<Integer> at runtime). When a method parameter is an array type with a wildcard bound like Object[], the same covariance rules apply — you can pass a String[] but the array's static type is Object[]."
11. What is the difference between List<?> and List<Object>?
List<?> means "a list of some unknown type" — the compiler knows nothing about the element type, so it only allows reads as Object and forbids all additions (except null). List<Object> means "a list of exactly Object" — the compiler allows both reads and writes of any type. List<Object> is a concrete parameterized type; List<?> is a wildcard type with unknown element type. The distinction matters: List<?> accepts any specific list; List<Object> only accepts lists of Object."
12. Can a class implement a generic interface with wildcard usage?
Yes. When a class implements a generic interface, the method signature can include wildcards. For example, class StringList implements List<String> has add(String), not add(?). But you could implement an interface method that uses a wildcard: void process(List<? extends Number> numbers) inside a class. The wildcard usage is in the method signature, not the class declaration."
13. How does the producer-consumer pattern use wildcards?
The producer-consumer pattern (PECS) uses wildcards at call sites to express data flow direction. If a method reads from a collection (produces elements), use ? extends T so the caller can pass List<Integer> for List<? extends Number>. If a method writes to a collection (consumes elements), use ? super T so the caller can pass List<Number> for List<? super Integer>. When a method does both, use the concrete type parameter instead of wildcards."
14. Can overloaded methods differ only in wildcard bounds?
No. `void process(List<? super Integer>)` and `void process(List<? super Double>)` have the same erased signature, `process(List)`, so Java reports a name clash. Use distinct method names or a single generic method when the operations are truly the same.
15. What are the pitfalls of using wildcards in varargs?
Yes, but with caveats. void printAll(List<?>... lists) collects varargs into an array. Since arrays and generics interact badly (heap pollution), the compiler warns. @SafeVarargs silences the warning. However, List<?> elements cannot have anything added to them except null, so the method can only read from each list or pass them to other methods that accept wildcards. Be cautious with varargs on generic collections."
16. How does Collections.copy work with super wildcards in practice?
This is the classic PECS implementation. src is ? extends T — it can produce T elements (read as T). dest is ? super T — it can consume T elements (accept T for writing). The T from src is compatible with ? super T because any supertype of T can hold T. The method works because the producer's type is compatible with the consumer's bound, regardless of the concrete types at the call site."
17. What happens when you assign a parameterized type to a wildcard reference?
`List<?> list = new ArrayList<String>();` is safe: you can read elements as `Object`, and the compiler blocks non-null writes because the element type is unknown. A raw alias or unchecked cast can bypass that protection, but a later read through `List<String>` may then throw `ClassCastException`.
18. Should you use wildcards as return types? Why or why not?
Java allows wildcard return types. They can suit an intentionally read-oriented API, but callers may have limited ways to use the result because its element type is unknown. Prefer a concrete type or a named type parameter when that gives callers a clearer contract.
19. How do wildcards relate to Optional types in Java?
Wildcards work with `Optional` as they do with other generic types. `Optional<Integer>` is not a subtype of `Optional<Number>`, but a method can accept `Optional<? extends Number>` and read its value as `Number`. `Optional` being value-based does not change generic variance.
20. Can wildcards be used in exception handling or lambda expressions?
No. You cannot use wildcards in a catch clause (catch (Exception<? extends Throwable> e) is a compile error). However, generic types can appear in exception declarations: a generic method can throw T extends Exception. In lambda expressions, you cannot declare generic exception parameters directly — you wrap them in a generic exception type or use a callback interface that declares the exception type. The JVM's exception handling does not support wildcard types."

Further Reading


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.

#java-abstract-classes #java #java-fundamentals

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-arithmetic-operators #java #java-fundamentals

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.

#java-array-basics #java #java-fundamentals