ArchitectMind
  1. Home
  2. Java Ecosystem
  3. Book 1 · Core Java & Modern Java
  4. Volume II
  5. PECS
Book 1 · Volume II — Generics, Collections & Type System · Topic 2.3

PECS

Producer extends, consumer super — with practical examples

10 min readStage 1 · Foundations15 interview questions
Prerequisites
2.2 Wildcards
Covers
Producer extends · Consumer super · Practical examples
Related
2.4 Type Inference · B1V3 (Function, Predicate, Collector signatures) · Book 5 (API design)
On this page
  1. 1. Concept / Definition
  2. 2. Why It Exists
  3. 3. Core Concepts
  4. 4. How It Works Internally
  5. 5. APIs / Features / Syntax
  6. 6. Practical Examples
  7. 7. Common Problems & Mistakes
  8. 8. Performance & Production Considerations
  9. 9. Architecture & Design Considerations
  10. 10. Interview Questions & Answers
  11. Key Takeaways

1Concept / Definition

PECS — Producer Extends, Consumer Super — is Joshua Bloch's mnemonic for choosing wildcards on method parameters. If a parameterised parameter produces values that your method reads, declare it ? extends T. If it consumes values that your method writes into it, declare it ? super T. If it does both, use the exact type T.

Values flow out of a producer (extends) and into a consumer (super)
Figure 1 — Values flow out of a producer (extends) and into a consumer (super)

The same rule is sometimes called the get-and-put principle (Naftalin and Wadler): use extends when you only get values out, super when you only put values in, and no wildcard when you do both.

The get-and-put principle
Figure 2 — The get-and-put principle

2Why It Exists

Wildcards (2.2) give three possible parameter types for the same idea, and choosing wrongly produces either APIs that are too rigid — callers cannot pass the collections they have — or code that does not compile. PECS turns the choice into a mechanical question about the direction of data flow, and it explains most generic signatures in the JDK.

3Core Concepts

Producer extends

A parameter is a producer when the method only reads T values from it: iterating a source collection, calling a Supplier, reading from an Iterable. Declaring it Collection<? extends T> lets callers pass collections of any subtype of T. Inside the method, every value read is safely a T.

Functions are producers of their result: Function<? super T, ? extends R> produces an R (so ? extends R), letting a function returning Integer be used where a Function returning Number is expected.

Consumer super

A parameter is a consumer when the method only puts T values into it: adding to a destination collection, passing values to a Consumer, Predicate or Comparator. Declaring it Collection<? super T> or Comparator<? super T> lets callers pass a collection or strategy written for any supertype of T.

Comparators, predicates and consumers are the most common consumers in practice: a Comparator<Employee> can sort a list of Managers, and a Predicate<Object> can filter anything.

A comparator for the supertype works for every subtype list
Figure 3 — A comparator for the supertype works for every subtype list

Practical examples

The JDK applies PECS consistently. Reading its signatures with the rule in mind makes them easy to understand:

PECS in Collections, Collection and Stream signatures
Figure 4 — PECS in Collections, Collection and Stream signatures
SignatureProducer / consumer analysis
Collections.copy(List<? super T> dest, List<? extends T> src)src produces T (extends); dest consumes T (super)
Collection<E>.addAll(Collection<? extends E> c)c produces E values to add
Collections.max(Collection<? extends T> coll, Comparator<? super T> comp)coll produces T; comp consumes T values
Stream<T>.map(Function<? super T, ? extends R> mapper)mapper consumes T (super) and produces R (extends)
Stream<T>.filter(Predicate<? super T> p)p consumes T
Iterable<T>.forEach(Consumer<? super T> action)action consumes T
Optional<T>.orElseGet(Supplier<? extends T> s)s produces T
PECS applies to parameters; return types should be exact
Figure 5 — PECS applies to parameters; return types should be exact

4How It Works Internally

PECS is purely a compile-time rule: the wildcards are erased, so a PECS-compliant signature has the same bytecode as a rigid one. The benefit is entirely in what the compiler will accept at call sites. Because widening a parameter from List<T> to List<? extends T> does not change its erasure, library authors can usually apply PECS to existing APIs without breaking binary compatibility.

5APIs / Features / Syntax

JAVAAll three parameter roles in one method
// Template for a method that reads from one collection and writes to another
public static <T> void transfer(Collection<? extends T> from,     // producer
                                Collection<? super T> to,         // consumer
                                Predicate<? super T> accept) {  // consumer of T
    for (T item : from) {
        if (accept.test(item)) to.add(item);
    }
}

List<Integer> ints = List.of(1, 2, 3, 4);
List<Number> numbers = new ArrayList<>();
Predicate<Object> notNull = Objects::nonNull;
transfer(ints, numbers, notNull);      // T = Integer; all three flexible

6Practical Examples

Example 1 — Rigid versus PECS signature

JAVAAdding a producer wildcard
// Rigid: only exact types work
static <T> void pushAll(Deque<T> stack, List<T> items) { items.forEach(stack::push); }
Deque<Number> stack = new ArrayDeque<>();
List<Integer> ints = List.of(1, 2);
// pushAll(stack, ints);  // error: T cannot be both Number and Integer

// PECS: items only produce values
static <T> void pushAll2(Deque<T> stack, Iterable<? extends T> items) {
    for (T t : items) stack.push(t);
}
pushAll2(stack, ints);  // OK: T = Number, items produce Integers
With the producer wildcard, one T satisfies both arguments
Figure 6 — With the producer wildcard, one T satisfies both arguments

Why it works. In the rigid version, Deque<Number> forces T = Number and List<Integer> forces T = Integer, so no T fits (Figure 6). With Iterable<? extends T>, T = Number satisfies both, because a list of Integer produces values that are Numbers. The parameter type changed, the body barely did, and every call that worked before still works.

Example 2 — Mini program: a top-N utility with all three roles

Problem. A reporting library needs one method that picks the best n items from any source, by any ordering, into any destination: managers ranked by an Employee comparator into a board of employees, or into an audit log of Objects.

JAVATopN.java
public class TopN {
    static class Employee {
        final String name;
        final int salary;
        Employee(String name, int salary) {
            this.name = name;
            this.salary = salary;
        }
        public String toString() { return name; }
    }
 
    static final class Manager extends Employee {
        final int reports;
        Manager(String name, int salary, int reports) {
            super(name, salary);
            this.reports = reports;
        }
    }
 
    // src produces T, order consumes T, sink consumes T
    static <T> void topN(Iterable<? extends T> src, int n,
                         Comparator<? super T> order,
                         Collection<? super T> sink) {
        PriorityQueue<T> best = new PriorityQueue<>(order); // smallest on top
        for (T item : src) {
            best.add(item);
            if (best.size() > n) best.poll();          // drop the smallest
        }
        List<T> result = new ArrayList<>(best);
        result.sort(order.reversed());                      // largest first
        sink.addAll(result);
    }
 
    public static void main(String[] args) {
        List<Manager> managers = List.of(new Manager("Asha", 210, 6),
                new Manager("Ben", 180, 4), new Manager("Chen", 240, 9));
        Comparator<Employee> bySalary = Comparator.comparingInt(e -> e.salary);
 
        List<Employee> board = new ArrayList<>();       // a supertype sink
        topN(managers, 2, bySalary, board);
        System.out.println("top 2 by salary:  " + board);
 
        List<Object> audit = new ArrayList<>(List.of("audit:"));
        Comparator<Manager> byReports = Comparator.comparingInt(m -> m.reports);
        topN(managers, 1, byReports, audit);
        System.out.println("most reports:     " + audit);
    }
}
OUTPUT
top 2 by salary:  [Chen, Asha]
most reports:     [audit:, Chen]

Why it behaves this way. The source only produces T values, so it is Iterable<? extends T>; the comparator only consumes them, so Comparator<? super T>; the sink only receives them, so Collection<? super T>. For the first call T is inferred as Manager, and a Comparator<Employee> and a List<Employee> are accepted because Employee is a supertype. A min-heap of size n keeps the largest items seen so far, which is why the result is sorted with order.reversed() before it goes to the sink. With exact types the method would need four overloads or copies at every call site.

Example 3 — Comparators and sorting

JAVAA supertype comparator used on a subtype list
class Employee { BigDecimal salary() { … } }
class Manager extends Employee { int reports() { … } }

Comparator<Employee> bySalary = Comparator.comparing(Employee::salary);
List<Manager> managers = loadManagers();
managers.sort(bySalary);  // List<Manager>.sort(Comparator<? super Manager>)

Why it works. sort is declared sort(Comparator<? super E>), so on a List<Manager> it accepts a Comparator<Employee>: every Manager is an Employee, so a comparator that compares employees can compare managers. Without ? super, each subtype would need its own comparator, or the list would have to be copied into a List<Employee>.

Example 4 — A domain event bus

JAVAPECS in an application-level API
public final class EventBus {
    private final Map<Class<?>, List<Consumer<Object>>> handlers = new ConcurrentHashMap<>();

    // consumer
    public <E> void subscribe(Class<E> type, Consumer<? super E> handler) {
        handlers.computeIfAbsent(type, t -> new CopyOnWriteArrayList<>())
                .add(event -> handler.accept(type.cast(event)));
    }

    // producer
    public void publishAll(Collection<? extends DomainEvent> events) {
        for (DomainEvent e : events) {
            handlers.getOrDefault(e.getClass(), List.of()).forEach(h -> h.accept(e));
        }
    }
}

// handler for a supertype
bus.subscribe(OrderPlaced.class, (DomainEvent e) -> audit.record(e));
Dispatch looks up the exact class: a supertype subscription receives nothing
Figure 7 — Dispatch looks up the exact class: a supertype subscription receives nothing

Why it works, and its limit. subscribe takes a Consumer<? super E>, so an audit handler written for every DomainEvent can subscribe to OrderPlaced, and the stored adapter casts with type.cast before calling it. publishAll takes Collection<? extends DomainEvent>, so a List<OrderPlaced> can be published directly. Dispatch, however, looks up e.getClass() exactly: in the kit's run, a handler subscribed to DomainEvent.class receives nothing (Figure 7). Q15 discusses the fix.

7Common Problems & Mistakes

MistakeConsequenceFix
extends on a parameter you write toCannot add; compile errors, because the argument may be a list of a subtypesuper, or exact type
super on a parameter you read fromReads give only Object; casts creep in; callers cast the results backextends
Wildcard on a parameter used for bothNeither read nor write works well; callers cannot pass the collections they haveExact type T (no wildcard)
Wildcards in return typesAwkward types for all callers, and nobody can add to what they receiveExact return types (Figure 5)
Forgetting ? super on Comparator/Predicate/Consumer parametersSupertype strategies rejected, so every subtype needs its own strategy objectComparator<? super T> etc.
A wildcard where the method returns the argument's type (List<? extends T> saveAll(...))Callers get an unknown type back and cannot use the entities they saved without casts<S extends T> List<S> saveAll(Iterable<S> entities)

8Performance & Production Considerations

No run-time impact. The practical production benefit is fewer copies (new ArrayList<>(subtypeList) just to satisfy a rigid signature) and fewer unchecked casts, which are both sources of subtle bugs and garbage.

PECS mistakes in a shared library are cheap to fix early and expensive later: once dozens of services have written copies and casts around a rigid signature, the workarounds survive long after the signature is fixed. Widening a parameter with a wildcard is binary compatible, because the erasure is the same, so it can ship in a minor release; check subclasses that override the method, which must be updated at the same time.

9Architecture & Design Considerations

PECS is part of the craft of designing reusable APIs — shared libraries, platform SDKs, internal frameworks. Applied consistently, it lets callers use their own domain hierarchies naturally: a generic Validator<? super T>, a Mapper<? super S, ? extends T>, a Repository.saveAll(Iterable<? extends T>). Spring Data's <S extends T> List<S> saveAll(Iterable<S> entities) shows the other half of the rule: because the method returns the saved entities with the caller's own type, it names that type with a bounded type parameter instead of a wildcard. Both it and the Stream API are good models to follow.

10Interview Questions & Answers

Q1L1 · BasicConcept

What does PECS stand for?

Producer Extends, Consumer Super: use ? extends T for parameters you read T values from, and ? super T for parameters you write T values into. The mnemonic is about the parameter's role for your method, not about the type itself: the same List<Order> is a producer for a method that sums it and a consumer for one that fills it.

Q2L1 · BasicConcept

What should you use when a parameter is both read from and written to?

The exact type, e.g. List<T>, with no wildcard. A wildcard would forbid either the reads or the writes. Collections.swap and List.sort work on the same list in both directions.

Q3L2 · IntermediateInternals

Explain the signature of Collections.copy.

copy(List<? super T> dest, List<? extends T> src): src only produces T values, so extends; dest only consumes them, so super. You can copy a List<Integer> into a List<Number> or List<Object>.

Q4L2 · IntermediateTricky

Why is the Comparator parameter of sort declared Comparator<? super T>?

The comparator consumes T values by comparing them, so any comparator written for T or a supertype works — a Comparator<Employee> can sort a List<Manager>. Sorting compares elements but never stores a comparator result in the list, so the comparator is a pure consumer of T.

Q5L3 · Senior EngineerInternals

Why does Stream.map take Function<? super T, ? extends R>?

The function consumes the stream's T elements (so it may accept any supertype of T) and produces R values (so it may return any subtype of R). This allows reusing general functions without adapters. For example, a Function<Object, String> such as Object::toString can map a Stream<Order> to a Stream<CharSequence>.

Q6L3 · Senior EngineerTricky

Does applying PECS change the bytecode of a method?

No. Wildcards are erased, so List<? extends T> and List<T> erase to List. The change affects only which calls compile, which also makes it binary-compatible for existing callers. It is the call sites that change: code that needed a copy or a cast before now compiles directly.

Q7L3 · Senior EngineerScenario

Your team's library method is void process(List<Event> events). Callers have List<OrderEvent>. What do you change and why?

If process only reads the events, change it to List<? extends Event> (or Collection<? extends Event>). Callers can then pass their subtype lists without copying or casting, and the change is source- and binary-compatible. Check that process really only reads; if it also adds events, the exact type is right and callers need a List<Event>.

Q8L3 · Senior EngineerDesign

Is PECS relevant for functional interfaces you design yourself?

Yes. Methods taking your functional interfaces should use ? super for the input type parameters and ? extends for output ones, e.g. <T, R> List<R> mapAll(Collection<? extends T> c, Mapper<? super T, ? extends R> m). For example, Mapper<? super T, ? extends R> lets a mapper written for Object produce a subtype of R, as Function does in Stream.map.

Q9L4 · Technical ArchitectTrade-off

How do you balance API flexibility with readability?

Apply wildcards to public parameters where callers benefit, keep return types exact, avoid more than two or three type parameters, and hide complex generic plumbing behind named domain types. Flexibility at the boundary, simplicity inside.

Q10L4 · Technical ArchitectDesign

How would you review a generic API for correctness and usability before publishing a platform library?

For each parameter, classify data flow and choose extends, super, exact or ?; ensure return types are exact; write compile tests calling the API with subtype collections and supertype strategies; check that no caller needs a cast; and verify binary compatibility of erasures against the previous version.

Q11L5 · Solution ArchitectTrade-off

How does disciplined generic API design affect an organisation with many teams consuming shared libraries?

Well-designed generic APIs let teams model their own domain hierarchies and still use shared components without adapters, copies or unchecked casts. Poor ones spread workarounds across dozens of services, which then resist library upgrades. Making PECS part of library review standards is a cheap way to keep a platform ecosystem healthy.

Q12L2 · IntermediateCode

What does this program print?

JAVAPecsQuiz.java
public class PecsQuiz {
    static <T> void transfer(Collection<? extends T> from,
                             Collection<? super T> to,
                             Predicate<? super T> accept) {
        for (T item : from) if (accept.test(item)) to.add(item);
    }
 
    public static void main(String[] args) {
        List<Integer> ints = List.of(1, 2, 3, 4);
        List<Number> numbers = new ArrayList<>(List.of(0.5));
        Predicate<Number> big = n -> n.doubleValue() > 2;
        transfer(ints, numbers, big);
        System.out.println(numbers);
        List<Object> all = new ArrayList<>();
        transfer(numbers, all, Objects::nonNull);
        System.out.println(all.size());
    }
}

It prints [0.5, 3, 4], then 3. In the first call T is inferred as Integer: the integers are produced from a List<Integer>, tested by a Predicate<Number> and added to a List<Number>, both supertypes. Only 3 and 4 pass, after the 0.5 already in the list. In the second call T is Number, and the method reference Objects::nonNull targets a Predicate<? super Number>, so all three elements are copied into the List<Object>.

Q13L3 · Senior EngineerCode

A Comparator<Object> sorts a List<Integer>. What does this program print?

JAVASortQuiz.java
public class SortQuiz {
    public static void main(String[] args) {
        Comparator<Object> byText = Comparator.comparing(Object::toString);
        List<Integer> xs = new ArrayList<>(List.of(10, 9, 100));
        xs.sort(byText);              // sort(Comparator<? super Integer>)
        System.out.println(xs);
        xs.sort(Comparator.naturalOrder());
        System.out.println(xs);
    }
}

It prints [10, 100, 9], then [9, 10, 100]. List<Integer>.sort accepts a Comparator<? super Integer>, so a comparator written for Object is allowed, and it compares the numbers as text: "10" < "100" < "9". The second sort uses the natural order of Integer. PECS makes the call legal; it does not make the comparator meaningful, so check what a supertype strategy really compares.

Q14L3 · Senior EngineerTricky

Collections.max returns a T. Why is its collection parameter Collection<? extends T> and not simply Collection<T>?

The collection is a pure producer, so PECS gives ? extends T, and the wildcard decouples T from the collection's declared element type. Collections.<Number>max(ints, byValue) compiles with a List<Integer> and returns a Number; with Collection<T> and T = Number it would be rejected, because a List<Integer> is not a Collection<Number>. In most calls inference hides the difference, which is exactly why the wildcard is worth having: it never costs a caller anything, documents the parameter's role, and leaves the erased signature unchanged.

Q15L4 · Technical ArchitectScenario

Teams using the event bus of Example 3 report that their audit handler, subscribed to DomainEvent.class, never fires. What is wrong, and how would you fix the bus?

The subscription side uses ? super E correctly, but dispatch looks up handlers.get(e.getClass()), and the class of a concrete event is never DomainEvent itself (Figure 7). The compiler cannot catch this: the types are right, the lookup rule is not. Fix the dispatch: for each event, walk its class, superclasses and interfaces and call the handlers registered for each, caching the resolved list per event class, for example in a ClassValue or a ConcurrentHashMap.

Then add a test that publishes a subtype event to a supertype handler. Alternatively, keep exact dispatch but document it and reject subscribe calls for interfaces and abstract classes, so the mistake fails loudly.

Test your knowledge on this topic →Try multiple choice →Flashcards from this topic's 15 questions, filtered by level and type.

Key Takeaways

  • Producer (you read from it): ? extends T.
  • Consumer (you write to it, or it receives T): ? super T.
  • Both: exact T. Neither: ?.
  • Comparators, predicates and consumers are consumers: ? super T.
  • Apply PECS to parameters only; keep return types exact.
Free question pack

Get 100 free Core Java interview questions

Subscribe for the Book 1 question pack (PDF, every answer explained) and new tutorials once a week. No spam, unsubscribe anytime. What is in the pack?

Almost done! Check your inbox and click the confirmation link. Your download link arrives as soon as you confirm.