-
Notifications
You must be signed in to change notification settings - Fork 4
PECS (Producer Extends Consumer Super)
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:
-
? extends T
wildcard is used in a Collection if you need to retrieve an object typeT
from that collection -
? super extends T
wildcard is used in a Collection if you need to insert an object typeT
into that collection - If you need to do to both, you cannot use a wildcard
Examples:
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
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.
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
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