Q34: What are Upper/Lower Bounded Wildcards and the PECS Principle?
? extends T(Upper Bound): AcceptsTor any subclass ofT.? super T(Lower Bound): AcceptsTor any superclass ofT.- PECS Rule: Producer Extends, Consumer Super.
- Use
? extends Twhen reading data out of a collection (Collection is a Producer). - Use
? super Twhen writing data into a collection (Collection is a Consumer).
- Use
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?