- 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
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.

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.

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.

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

| Signature | Producer / 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 |

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
// 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 flexible6Practical Examples
Example 1 — Rigid versus PECS signature
// 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
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.
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);
}
}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
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
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));
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
| Mistake | Consequence | Fix |
|---|---|---|
| extends on a parameter you write to | Cannot add; compile errors, because the argument may be a list of a subtype | super, or exact type |
| super on a parameter you read from | Reads give only Object; casts creep in; callers cast the results back | extends |
| Wildcard on a parameter used for both | Neither read nor write works well; callers cannot pass the collections they have | Exact type T (no wildcard) |
| Wildcards in return types | Awkward types for all callers, and nobody can add to what they receive | Exact return types (Figure 5) |
| Forgetting ? super on Comparator/Predicate/Consumer parameters | Supertype strategies rejected, so every subtype needs its own strategy object | Comparator<? 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
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.
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.
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>.
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.
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>.
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.
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>.
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.
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.
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.
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.
What does this program print?
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>.
A Comparator<Object> sorts a List<Integer>. What does this program print?
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.
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.
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.