什么是PECS(制片人扩大消费者超级)? [英] What is PECS (Producer Extends Consumer Super)?
问题描述
我遇到了PECS(简称 Producer extends
和Consumer super
))阅读泛型。
有人可以向我解释如何使用PECS解决 extends
和 super之间的混淆?
tl; dr:收藏的观点。如果你只是从一个通用集合中抽取项目,它是一个生产者,你应该使用 extends
;如果你只是填充物品,它是一个消费者,你应该使用 super
。如果你同时使用同一个集合,则不应该使用 extends
或 super
。
假设你有一个方法以参数为参数集合,但你希望它比接受 Collection< Thing>
。
案例1:您想要浏览收藏并对每件物品进行操作。
然后,列表是生产者,因此您应该使用集合<?扩展Thing>
。
推理是一个 Collection< ;?扩展Thing>
可以包含 Thing
的任何子类型,因此每个元素将表现为 Thing $ c $当你执行你的操作时。 (你实际上不能在
集合< ;? extends Thing>
中添加任何东西,因为你不能在运行时知道特定的子类型>物品
集合成立。)
情况2:您想要将物品添加到集合中。 >
然后列表是一个消费者,所以您应该使用集合<超级事物>
。
这里的推理与 Collection <? extends Thing>
, Collection <?不管实际的参数化类型是什么,超级事物>
总是可以持有 Thing
。在这里,只要它允许添加 Thing
,您就不会在乎列表中的内容;这是?超级事情
保证。
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
?
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 use super
. If you do both with the same collection, you shouldn't use either extends
or 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 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.
这篇关于什么是PECS(制片人扩大消费者超级)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!