java - What is PECS (Producer Extends Consumer Super)? -
i came across pecs (short producer extends , consumer super) while reading on generics.
can explain me how use pecs resolve confusion between extends , super?
tl;dr: "pecs" collection's point of view. if only pulling items generic collection, producer , should use extends; if only stuffing items in, consumer , should use super. if both same collection, shouldn't use either extends or super.
suppose have method takes parameter collection of things, want more flexible accepting collection<thing>.
case 1: want go through collection , things each item.
list producer, should use collection<? extends thing>.
the reasoning collection<? extends thing> hold subtype of thing, , each element behave thing when perform operation. (you cannot add collection<? extends thing>, because cannot know @ runtime specific subtype of thing collection holds.)
case 2: want add things collection.
list consumer, should use collection<? super thing>.
the reasoning here unlike collection<? extends thing>, collection<? super thing> can hold thing no matter actual parameterized type is. here don't care in list long allow thing added; ? super thing guarantees.
Comments
Post a Comment