Q34: What are Upper/Lower Bounded Wildcards and the PECS Principle?

  • ? extends T (Upper Bound): Accepts T or any subclass of T.
  • ? super T (Lower Bound): Accepts T or any superclass of T.
  • PECS Rule: Producer Extends, Consumer Super.
    • Use ? extends T when reading data out of a collection (Collection is a Producer).
    • Use ? super T when writing data into a collection (Collection is a Consumer).
PECS Demonstration
// Producer: Reading items out
public void processNumbers(List<? extends Number> list) {
    for (Number n : list) { System.out.println(n); }
}

// Consumer: Writing items in
public void addIntegers(List<? super Integer> list) {
    list.add(100); // Legal write
}
💡 extends allows safe reads of Number; super allows safe writes of Integer objects.
Key Takeaways
  • Producer Extends (? extends T) = Read-only extraction. Consumer Super (? super T) = Write-only insertion.
Knowledge Check

According to PECS, which wildcard should be used on a method parameter list that you ONLY insert items INTO?