0Pricing
Java Academy · Lesson

The PECS Principle

Producer Extends, Consumer Super.

What PECS Stands For

PECS means Producer Extends, Consumer Super. It is a mnemonic from Joshua Bloch's Effective Java.

  • If a parameter produces T (you read from it), use ? extends T.
  • If a parameter consumes T (you write to it), use ? super T.
public class Main {
    public static void main(String[] args) {
        System.out.println("Producer Extends, Consumer Super");
    }
}

The Canonical copy Method

The classic PECS example is a copy method. The source produces, so it is ? extends T. The destination consumes, so it is ? super T.

import java.util.ArrayList;
import java.util.List;

public class Main {
    static <T> void copy(List<? extends T> src, List<? super T> dest) {
        for (T t : src) dest.add(t);
    }
    public static void main(String[] args) {
        List<Integer> src = List.of(1, 2, 3);
        List<Object> dest = new ArrayList<>();
        copy(src, dest);
        System.out.println(dest);
    }
}

All lessons in this course

  1. Upper Bounded Wildcards
  2. Lower Bounded Wildcards
  3. The PECS Principle
  4. Wildcards in APIs
← Back to Java Academy