Junior — Middle
What is the purpose of the PECS method in software development?
sobes.tech AI
Answer from AI
PECS is a principle used when working with generics in Java, which helps correctly utilize covariance and contravariance of collections. The abbreviation stands for "Producer Extends, Consumer Super".
- If an object acts as a data producer, the
? extends Trestriction is used — this allows reading data of type T or its subtypes. - If an object acts as a data consumer, the
? super Trestriction is used — this allows writing data of type T or its subtypes.
For example:
List<? extends Number> producer = new ArrayList<Integer>();
Number num = producer.get(0); // reading is allowed
// producer.add(10); // error, cannot add
List<? super Integer> consumer = new ArrayList<Number>();
consumer.add(10); // adding is allowed
// Integer i = consumer.get(0); // error, type cannot be guaranteed when reading
Thus, PECS helps avoid type errors when working with generic collections and improves type safety.