Course contentsShow
← Java
Lesson 944 of 2,87022. Generics: Bounds and WildcardsFree lesson

Real-World Example: Collections.copy and PECS

Analyzing how Collections.copy uses PECS with source as producer and destination as consumer.

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.copy will read
  • You only need to read from the source, never write to it
  • ? extends T guarantees every element is at least a T (or subtype)

Destination list uses ? super T because it's a consumer:

  • The destination list consumes elements that Collections.copy will write
  • You only need to write to the destination, not read specific types back
  • ? super T guarantees the list can accept any T you 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.