What is PECS (Producer Extends Consumer Super)?

原文链接:https://*.com/questions/2723397/what-is-pecs-producer-extends-consumer-super

"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 use super. If you do both with the same collection, you shouldn't use either extends or super.

PECS来自集合中的观念。如果你仅仅从集合中取数据使用,那么集合就是个生产者,你应该使用extends。如果你向集合中添加数据,那么集合对你来说是个消费者,你应该使用super。如果你两种操作都有,那么就都不要用。


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 specificsubtype of Thing the collection holds.)

如果你想从集合中拉取数据,你需要使用Collection<? extends Thing>的集合,这是因为:Collection<? extends Thing>可装任何Thing的物品。但是你不能操作Collection<? extends Thing>集合,因为运行时里面到底装的具体那种类型。

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 Thingguarantees.

如果你向集合中添加数据,那你应该使用Collection<? super Thing>。原因是:Collection<? super Thing>中的对象一定是Thing及Thing的父类。

其实上本质上就是因为java里只支持上转型。

上一篇:JAVA的PECS原则


下一篇:什么是PECS,细说Java中的extends和super