Real-World Example: Collections.copy and PECS
You'll learn how Java's Collections.copy method uses PECS to safely copy elements between lists.
The Collections.copy Method Signature
Java's standard library provides a perfect example of PECS in action:
public static <T> void copy(List<? super T> dest, List<? extends T> src)
Notice how the method uses both wildcard types we've learned about.
Breaking Down the PECS Application
Source list uses ? extends T because it's a producer:
- The source list produces elements that
Collections.copywill read - You only need to read from the source, never write to it
? extends Tguarantees every element is at least aT(or subtype)
Destination list uses ? super T because it's a consumer:
- The destination list consumes elements that
Collections.copywill write - You only need to write to the destination, not read specific types back
? super Tguarantees the list can accept anyTyou put in
Why This Design Works
This signature allows maximum flexibility:
List<Number> numbers = new ArrayList<>();
List<Integer> integers = Arrays.asList(1, 2, 3);
Collections.copy(numbers, integers); // Works!
// integers produces Integer (extends Number)
// numbers consumes Number (super Integer)
Without PECS, you'd need exact type matches, making the method far less useful.
Key Takeaway: Collections.copy exemplifies PECS perfectly—the source parameter uses ? extends T to produce elements for reading, while the destination uses ? super T to consume elements for writing, creating a flexible and type-safe API.