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

PECS in Method Signatures: Designing Flexible APIs

Applying PECS to write methods that accept the widest possible range of argument types.

PECS in Method Signatures: Designing Flexible APIs

What you'll learn: How to apply the PECS principle when designing method signatures that accept the widest possible range of argument types.

Why Method Signatures Matter

When you design a method's parameters, you control what callers can pass. By applying PECS (Producer Extends, Consumer Super), you make your API flexible enough to accept more argument types without breaking type safety.

The Design Strategy

Use ? extends T when your method reads from a parameter (the parameter produces data for you):

public void processNumbers(List<? extends Number> numbers) {
    for (Number n : numbers) {
        System.out.println(n.doubleValue());
    }
}

This accepts List<Integer>, List<Double>, List<Number>, etc. You're only reading, so upper bounds work perfectly.

Use ? super T when your method writes to a parameter (the parameter consumes data from you):

public void addIntegers(List<? super Integer> list) {
    list.add(42);
    list.add(100);
}

This accepts List<Integer>, List<Number>, List<Object>, etc. You're only writing Integer values, so lower bounds ensure safety.

Real API Design

Compare these two signatures:

// Too restrictive: only accepts List<String>
public void printAll(List<String> items) { ... }

// Flexible: accepts List<String>, ArrayList<String>, etc.
public void printAll(List<? extends String> items) { ... }

The second signature respects PECS for a read-only operation, making your method callable in more situations.

Key Takeaway: Apply PECS when designing method parameters—use ? extends T for parameters you read from (producers) and ? super T for parameters you write to (consumers) to create maximally flexible, type-safe APIs.