Skip to content

Visualization for PECS

jaxsen31 edited this page Nov 13, 2021 · 3 revisions

PECS

PECS, or 'Producer Extends, Consumer Super', is a concept taught with regards to Collections and Generics in Java. It is meant to be used from the collection's viewpoint: If you, the user of the collection, are taking objects from a generic collection, the collection is thus producing objects and thus it should use extend with its generic wildcard; on the other hand, if you are adding objects into a collection, the collection is consuming and thus should use super with its generic wildcard.

While this explanation of PECS uses Collections as the use case, PECS can be abstracted and be applied to all uses of Generics in Java. This includes uses in functional interfaces (e.g. Function<? super T, ? extends U>) as many functions take in inputs and give out outputs so they are similar to Collections in the 'Producer' and 'Consumer' sense of PECS.

Examples

1. You want to access a collection and do things with each item

Here, the list is producing the objects you, the user, wants to use, so you should use a Collection<? extends Thing>.

The reason is that a Collection<? extends Thing> could hold any subtype of Thing, and thus each element will behave as a Thing when you perform your operation. (You actually cannot add anything (except null) to a Collection<? extends Thing>, because you cannot know at runtime which specific subtype of Thing the collection holds.)

2. You want to add things to the collection

Here, the list is a consumer as it is 'consuming' the objects you, the user, are providing, so you should use a Collection<? super Thing>.

The reason is that unlike Collection<? extends Thing>, Collection<? super Thing> can always hold a Thing no matter what the actual parameterized type is. Here you don't care what is already in the list as long as it will allow a Thing to be added; this is what ? super Thing guarantees.

Clone this wiki locally