-
Notifications
You must be signed in to change notification settings - Fork 4
Visualization for 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.
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.)
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
.
Peer Learning
Guides
Setting Up Checkstyle
Setting Up Java
Setting Up MacVim
Setting Up Stu
Setting Up Unix For Mac
Setting Up Unix For Windows
Setting Up Vim
Setting up SSH Config
SSH Without Password
Copying Files From PE Nodes
Using tmux
CS2030 Contents
Lecture 1 SummaryLecture 2 Summary
Access Modifiers
Lecture 3 Summary (Polymorphism)
Compile Time Type VS Runtime Type
Abstraction, Encapsulation, Inheritance, and Polymorphism
SOLID Principles
Class VS Abstract Class VS Interface
Comparable VS Comparator
Generic Types T
HashMap
Raw Types with Generic
Lambda expression
PECS (Producer Extends Consumer Super)
Optional
Streams
Parallel Streams
Monad
Functors and Monads with Category Theory