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

The PECS Principle: Producer Extends, Consumer Super

Understanding the mnemonic that guides when to use extends vs super wildcards in generic types.

The PECS Principle: Producer Extends, Consumer Super

You'll learn: A simple mnemonic to remember when to use extends vs super wildcards in generic collections.

What Is PECS?

PECS stands for "Producer Extends, Consumer Super"—a rule of thumb coined by Joshua Bloch to help you choose the right wildcard. Here's the breakdown:

  • Producer Extends: If a collection is producing values for you to read (you're taking items out), use <? extends T>. Think of it as the collection producing data that flows toward your code.

  • Consumer Super: If a collection is consuming values you provide (you're putting items in), use <? super T>. The collection consumes data flowing from your code into it.

Why This Matters

When you learned bounded wildcards, you saw that <? extends T> allows safe reading but not writing, while <? super T> allows safe writing but only reads as Object. PECS helps you remember which situation calls for which wildcard.

PECS in Action

// Producer scenario: reading from a source
public void processNumbers(List<? extends Number> producer) {
    for (Number n : producer) {  // Reading (producing values for us)
        System.out.println(n.doubleValue());
    }
}

// Consumer scenario: writing to a destination
public void addIntegers(List<? super Integer> consumer) {
    consumer.add(42);  // Writing (consuming values from us)
    consumer.add(100);
}

The collection "produces" when you iterate/read from it. It "consumes" when you add elements to it.

Memory Aid

Think of a vending machine: you extend your hand to get (produce) items from it. You feed coins into it as it supervises your purchase (consumes).

Key Takeaway:
Use PECS to guide wildcard choice: <? extends T> when reading (producer), <? super T> when writing (consumer).