Sobes.tech
Junior — Middle

Can you give a specific example of applying the PECS principle in software development?

sobes.tech AI

Answer from AI

The PECS principle (Producer Extends, Consumer Super) helps correctly use generics in Java to ensure flexibility and type safety when working with collections.

Example: if a method should accept a collection from which it only reads objects (producer), the type parameter is declared with extends. If the method only adds objects to the collection (consumer), super is used.

import java.util.List;

// Method that reads elements from a list (Producer)
public void processElements(List<? extends Number> list) {
    for (Number n : list) {
        System.out.println(n);
    }
}

// Method that adds elements to a list (Consumer)
public void addElements(List<? super Integer> list) {
    list.add(10);
    list.add(20);
}

Here, List<? extends Number> guarantees that you can safely read elements as Number, but cannot add new ones, while List<? super Integer> allows adding Integer and its subclasses, but reading returns Object.

Can you give a specific example of applying the PECS… - sobes.tech