Skip to content

PECS (Producer Extends Consumer Super)

Brendan Cheong Ern Jie edited this page Nov 6, 2021 · 2 revisions

What is PECS?

When using Java Generics and Collections (List, ArrayList, Queue etc..) its important to know whether you can insert items into a collection or retrieve items from that collection depending on ? extends T or ? super T.

In summary:

  1. ? extends T wildcard is used in a Collection if you need to retrieve an object type T from that collection
  2. ? super extends T wildcard is used in a Collection if you need to insert an object type T into that collection
  3. If you need to do to both, you cannot use a wildcard

Examples:

Producer Extends

Here is an example of Producer Extends. Think of a PE as the list giving you the items/producing items when called upon

List<? extends String> wildList = List.of("hello", "world");
String hello = wildList.get(0); // this is valid, no compile error

wildList.add("wassup") // this will throw an incompatible type error

Why can this occur? At runtime, java has no way of telling whether your inserted type will be a subtype or supertype of the list type. Basically, your argument in .add() could be a type that was extended and java wouldn't know it. So it throws an error

Consumer Super

Here is an example of Consumer Super. Think of CS as the list allowing items to be inserted/consuming items given

List<? super String> superList = List.of("hello", "world")
superList.add("wassup") // this is valid, no compile error

String hello = superList.get(0); // this will throw an incompatible type error

Why can this occur? At runtime, the type of list can be any type above String. The compiler can compile your assignment statement (which seems correct) but, at runtime the type of hello can be lower in hierarchy than the declared type of the list (Lower than String). This is not allowed so as to avoid runtime errors.

Visualisation for PECS

Came across this while searching about for answers regarding generics and PECS. It really helped me to visualize the idea of PECS, makes it a lot easier to picture and understand.

Link to original post: https://stackoverflow.com/questions/2723397/what-is-pecs-producer-extends-consumer-super

Clone this wiki locally