Skip to main content
๐Ÿ“œ WAYPOINT LESSON

Wildcards & PECS

โญโญ intermediateโณ 15 min read๐Ÿ“ Lesson 72 of 180

Producer Extends, Consumer Super: restoring flexibility to invariant generics and why extends-wildcards ban writes.

Wildcards and PECS

Integer is a Number, but List<Integer> is NOT a List<Number> โ€” generics are invariant. Wildcards restore flexibility safely:

static double sum(List<? extends Number> src) {   // producer: read out
    double t = 0;
    for (Number n : src) t += n.doubleValue();
    return t;
}

static void fill(List<? super Integer> dst) {     // consumer: write in
    dst.add(1); dst.add(2); dst.add(3);
}

PECS (from Effective Java): Producer Extends, Consumer Super.

  • If the parameter produces values for you โ†’ ? extends T
  • If the parameter consumes values from you โ†’ ? super T
  • Both (e.g. copy) โ†’ use both wildcards.

Why ? extends forbids writes: the compiler only knows "some unknown subtype of Number" โ€” any specific element you add might be the wrong one. Reads are always safe; writes are not, so they are banned.