Generics · Topic 6 of 7
PECS (producer extends, consumer super)
Definition​
PECS means: if a collection only gives you values, use ? extends T (producer extends). If it only receives values, use ? super T (consumer super). It makes a method accept more types while staying type-safe.
Example code​
Copy from a producer into a consumer
import java.util.ArrayList;
import java.util.List;
class Demo {
// source produces Ts (extends), destination consumes Ts (super)
static <T> void copy(List<? extends T> source, List<? super T> destination) {
for (T item : source) destination.add(item);
}
public static void main(String[] args) {
List<Integer> integers = List.of(1, 2, 3);
List<Number> numbers = new ArrayList<>();
List<Object> objects = new ArrayList<>();
copy(integers, numbers); // Integers can go into a list of Number
copy(integers, objects); // and into a list of Object
System.out.println(numbers);
System.out.println(objects);
}
}
// Output:
// [1, 2, 3]
// [1, 2, 3]
Finished this page? Track your progress (saved only in your browser).