I came across PECS (short for Producer extends and Consumer super) while reading up on generics.
Can someone explain to me how to use PECS to resolve confusion between extends and super?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
tl;dr: "PECS" is from the collection’s point of view. If you are only pulling items from a generic collection, it is a producer and you should use
extends; if you are only stuffing items in, it is a consumer and you should usesuper. If you do both with the same collection, you shouldn’t use eitherextendsorsuper.Suppose you have a method that takes as its parameter a collection of things, but you want it to be more flexible than just accepting a
Collection<Thing>.Case 1: You want to go through the collection and do things with each item.
Then the list is a producer, so you should use a
Collection<? extends Thing>.The reasoning is that a
Collection<? extends Thing>could hold any subtype ofThing, and thus each element will behave as aThingwhen you perform your operation. (You actually cannot add anything (except null) to aCollection<? extends Thing>, because you cannot know at runtime which specific subtype ofThingthe collection holds.)Case 2: You want to add things to the collection.
Then the list is a consumer, so you should use a
Collection<? super Thing>.The reasoning here is that unlike
Collection<? extends Thing>,Collection<? super Thing>can always hold aThingno matter what the actual parameterized type is. Here you don’t care what is already in the list as long as it will allow aThingto be added; this is what? super Thingguarantees.