Sobes.tech
Middle+

What is the PECS principle and how is it applied in Java?

sobes.tech AI

Answer from AI

The PECS principle (Producer Extends Consumer Super) is a mnemonic rule for determining when to use the keywords extends and super with wildcard types in Java generics.

  • Producer: When you use a generic parameter for retrieving data (extracting elements from a collection), use a wildcard with extends. The collection acts as a data producer. The type ? extends T means "any type that is T or a subclass of T." You can safely read elements as type T (or its superclass), but cannot add elements to such a collection (except null).

  • Consumer: When you use a generic parameter for adding data (placing elements into a collection), use a wildcard with super. The collection acts as a data consumer. The type ? super T means "any type that is T or a superclass of T." You can safely add elements of type T (or its subclasses) to such a collection, but when reading elements, you will get them as Object.

Application in Java:

Used with wildcard types (?) to increase API flexibility, working with collections or other generic types, allowing them to operate with a broader range of types while maintaining type safety.

Examples:

// Producer example
// The printAll method reads from a List
public void printAll(List<? extends Number> list) {
    // Can read elements as Number (or Object)
    for (Number num : list) {
        System.out.println(num);
    }
    // Cannot add elements (except null)
    // list.add(123); // Compilation error
}

// Consumer example
// The addNumbers method adds to a List
public void addNumbers(List<? super Integer> list) {
    // Can add Integer or its subclasses
    list.add(1);
    list.add(new Integer(2));
    // list.add(new Double(3.0)); // Compilation error

    // When reading, get Object
    Object o = list.get(0);
}