什么是 PECS(生产者扩展消费者超级)? [英] What is PECS (Producer Extends Consumer Super)?
问题描述
我在阅读泛型时遇到了 PECS(Producer extends
和 Consumer super
的缩写).
I came across PECS (short for Producer extends
and Consumer super
) while reading up on generics.
谁能向我解释一下如何使用 PECS 来解决 extends
和 super
之间的混淆?
Can someone explain to me how to use PECS to resolve confusion between extends
and super
?
推荐答案
tl;dr:是从集合的角度来看.如果你只从一个泛型集合中提取项目,它是一个生产者,你应该使用extends
;如果你只往里面塞东西,它就是一个消费者,你应该使用super
.如果您使用相同的集合同时执行这两项操作,则不应使用 extends
或 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
.
假设您有一个将事物集合作为其参数的方法,但您希望它比仅接受一个Collection
更灵活.
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>
.
案例 1:您想浏览集合并处理每个项目.
那么列表是一个生产者,所以你应该使用一个Collection
.
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>
.
推理是 Collection
可以包含 Thing
的任何子类型,因此当您执行操作时,每个元素都将表现为 Thing
.(实际上您不能向 Collection extends Thing>
添加任何内容(除了 null),因为您无法在运行时知道 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 (except null) to a Collection<? extends Thing>
, because you cannot know at runtime which specific subtype of Thing
the collection holds.)
案例 2:您想向集合中添加内容.
那么列表是一个消费者,所以你应该使用一个Collection
.
Case 2: You want to add things to the collection.
Then the list is a consumer, so you should use a Collection<? super Thing>
.
这里的推理是不像 Collection
,集合
总是可以保存一个 Thing
.在这里,您不关心列表中已有的内容,只要它允许添加 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屋!