Junior — Middle
Can you explain how the PECS principle is applied in programming?
sobes.tech AI
Answer from AI
The PECS principle (Producer Extends, Consumer Super) is used in Java for the correct application of covariance and contravariance in generics. It helps determine when to use extends and when to use super in type parameters.
- Producer Extends: If an object acts as a data source (producer), use
? extends T. This allows reading objects of type T or its subtypes but prohibits adding new elements. - Consumer Super: If an object acts as a data consumer, use
? super T. This allows adding objects of type T or its subtypes, but reading is limited.
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 is only allowed as Object
Thus, PECS helps avoid errors when working with generics, ensuring type safety.