Junior — Middle
Explain what the PECS principle means in the field of software development
sobes.tech AI
Answer from AI
The PECS principle (Producer Extends, Consumer Super) helps correctly use covariance and contravariance in Java generics when working with collections.
- Producer Extends (PE): if an object acts as a data source (producer), use
? extends T. This allows reading objects of type T or its subtypes. - Consumer Super (CS): if an object acts as a data consumer, use
? super T. This allows writing objects of type T or its subtypes.
Example:
List<? extends Number> producer = new ArrayList<Integer>();
Number num = producer.get(0); // can read
// producer.add(10); // error, cannot add
List<? super Integer> consumer = new ArrayList<Number>();
consumer.add(10); // can add
Object obj = consumer.get(0); // reading returns Object
Thus, PECS helps avoid type errors when working with generic collections, ensuring safety and flexibility of the code.