Senior
What is the acronym PECS (Producer Extends, Consumer Super) in Java generics?
sobes.tech AI
Answer from AI
The PECS acronym (Producer Extends, Consumer Super) helps correctly use bounded wildcard types in Java Generics for collections and other generic types.
-
Producer Extends: if an object acts as a source (producer) of data, use
? extends T. This allows reading elements of type T or its subtypes, but prohibits adding elements to avoid breaking type safety. -
Consumer Super: if an object acts as a consumer of data, use
? super T. This allows adding elements of type T or its subtypes, but reading returns objects of type Object or its supertype.
Example:
List<? extends Number> producer = new ArrayList<Integer>();
Number num = producer.get(0); // Reading is allowed
// producer.add(10); // Compilation error
List<? super Integer> consumer = new ArrayList<Number>();
consumer.add(10); // Adding is allowed
Object obj = consumer.get(0); // Reading returns Object
Thus, PECS helps determine when to use extends for reading (producer) and super for writing (consumer). This increases flexibility and safety of code with generics.