Core Java: The PECS rule - an extends wildcard produces, a super wildcard consumes

A List<? extends Number> is safe to read from because every element is at least a Number, while a List<? super Integer> is safe to write Integers into because it holds Integer or some supertype.

Code
static double sum(List<? extends Number> producer) {
    double total = 0;
    for (Number n : producer) total += n.doubleValue();
    return total;
}
static void fill(List<? super Integer> consumer, int count) {
    for (int i = 1; i <= count; i++) consumer.add(i);
}
List<Integer> ints = List.of(1, 2, 3);
System.out.println("Sum: " + sum(ints));
List<Number> target = new ArrayList<>();
fill(target, 3);
System.out.println("Filled: " + target);
Output
Sum: 6.0
Filled: [1, 2, 3]
Advertisement
More in JAVA

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-09-27

© Java Coding Hub · About · Contact · Privacy · Terms