Video in progress

Middle ☕ Core Java

What is the difference between ? extends T and ? super T in generics? Explain the PECS rule.

? extends T means "T or its descendant": you read from it but can't write to it (a producer). ? super T means "T or its ancestor": you can write a T into it, but what you read back is only Object (a consumer). PECS: Producer Extends, Consumer Super.

📖 Answer

Why a plain List<Number> isn't enough: List<Integer> is not a subtype of List<Number>. Otherwise you could do this:

List<Integer> ints = new ArrayList<>();
List<Number> nums = ints;    // if this were allowed...
nums.add(3.14);              // a Double would land inside ints

extends is for reading:

double sum(Collection<? extends Number> items) {
    double s = 0;
    for (Number n : items) s += n.doubleValue();  // reading is safe
    return s;
}
sum(List.of(1, 2, 3));        // a List<Integer> works
sum(List.of(1.5, 2.5));       // and so does a List<Double>

items.add(...): the compiler doesn't allow it, because it doesn't know exactly which type is inside.

super is for writing:

void fill(List<? super Integer> target) {
    for (int i = 0; i < 3; i++) target.add(i);    // writing an Integer is safe
}
fill(new ArrayList<Number>());
fill(new ArrayList<Object>());

A classic example from the JDK:

public static <T> void copy(List<? super T> dest, List<? extends T> src)

The rule: if you only read from a parameter, use extends; if you only write to it, use super; if you need both, use an exact T. Don't use a wildcard in the return type: it's awkward for the caller.