views:

436

answers:

2

Hi,

I came across PECS (short for Producer extends and Consumer super) while reading on Generics.

Can someone explain to me how to use PECS to resolve confusion between extends and super?

Thanks in advance!

+1  A: 

See my answer to another question here. I think it answers your question pretty well. Note that generally you should only be using ? extends T and ? super T for the parameters of some method. Methods should just use T as the type parameter on a generic return type.

ColinD
+22  A: 

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 of Thing, and thus each element will behave as a Thing when you perform your operation. (You actually cannot add anything to a Collection<? extends Thing>, because you cannot know at runtime which specific subtype of Thing the 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 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.

Michael Myers
epic explanation.
Justin
+1, very nice explanation - the icing being that if the method does both cases, one can't make it more flexible than Collection of Thing.
Carl