Phase 15 of 20 · Topic 15.3

Bounded Wildcards & the PECS Principle (? extends vs ? super)

1Concept

PECS stands for: Producer Extends, Consumer Super. If a parameterized collection produces data (`read`), use `? extends T` (Covariance). If a collection consumes data (`write`), use `? super T` (Contravariance). If you do both, use exact type `T`.

2Architecture Diagram

Producer Extends (READ ONLY):  List<? extends Number> ---> can read Number, CANNOT add elements!
Consumer Super   (WRITE ONLY): List<? super Integer>   ---> can add Integer, cannot read specific type!

3Code Example

Core Java
import java.util.ArrayList;
import java.util.List;

public class PecsPrincipleDemo {
    // PRODUCER: Reads numbers to calculate sum
    public static double sumOfList(List<? extends Number> list) {
        double sum = 0.0;
        for (Number n : list) sum += n.doubleValue();
        return sum;
    }

    // CONSUMER: Adds integers into destination
    public static void addIntegers(List<? super Integer> list) {
        list.add(100);
        list.add(200);
    }

    public static void main(String[] args) {
        List<Double> doubleList = List.of(1.5, 2.5, 3.0);
        System.out.println("Sum of doubles: " + sumOfList(doubleList));

        List<Number> numList = new ArrayList<>();
        addIntegers(numList); // Accepts List<Number> because Number is super of Integer
        System.out.println("numList populated: " + numList);
    }
}

4Expected Output

Sum of doubles: 7.0
numList populated: [100, 200]

5Key Takeaways

  • Remember: Producer Extends, Consumer Super (PECS).
  • `List<Object>` is NOT a supertype of `List<String>`; Generics are invariant by default.
  • `List<?>` is an unbounded wildcard shorthand for `List<? extends Object>`.