tl;dr: "PECS" is from the collection's point of view.
(tl; dr: “ PECS”是从集合的角度来看的。)
If you are only pulling items from a generic collection, it is a producer and you should use extends
; (如果您仅从通用集合中提取项目,则它是生产者,应使用extends
;)
if you are only stuffing items in, it is a consumer and you should use super
. (如果您仅将物品塞入其中,则它是消费者,您应该使用super
。)
If you do both with the same collection, you shouldn't use either extends
or super
. (如果您对同一个集合都进行了处理,则不应同时使用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>
.
(假设您有一个方法以事物的集合为参数,但是您希望它比仅接受Collection<Thing>
更为灵活。)
Case 1: You want to go through the collection and do things with each item.
(情况1:您想浏览集合并为每个项目做事。)
Then the list is a producer , so you should use a Collection<? extends Thing>
(那么列表是生产者 ,因此您应该使用Collection<? extends Thing>
)
Collection<? extends Thing>
. (Collection<? extends Thing>
。)
The reasoning is that a Collection<? extends Thing>
(原因是Collection<? extends Thing>
)
Collection<? extends Thing>
could hold any subtype of Thing
, and thus each element will behave as a Thing
when you perform your operation. (Collection<? extends Thing>
可以包含Thing
任何子类型,因此执行操作时每个元素都将像Thing
一样Thing
。)
(You actually cannot add anything to a Collection<? extends Thing>
, because you cannot know at runtime which specific subtype of Thing
the collection holds.) ((实际上,您不能将任何东西添加到Collection<? extends Thing>
,因为您无法在运行时知道该集合包含Thing
的哪个特定子类型。))
Case 2: You want to add things to the collection.
(情况2:您想向集合中添加内容。)
Then the list is a consumer , so you should use a Collection<? super Thing>
(那么列表是一个使用者 ,因此您应该使用Collection<? super Thing>
)
Collection<? super Thing>
. (Collection<? super Thing>
。)
The reasoning here is that unlike Collection<? extends Thing>
(这里的原因是与Collection<? extends Thing>
)
Collection<? extends Thing>
, Collection<? super Thing>
(Collection<? extends Thing>
, Collection<? super Thing>
)
Collection<? super Thing>
can always hold a Thing
no matter what the actual parameterized type is. (无论实际的参数化类型是什么, Collection<? super Thing>
始终可以容纳Thing
。)
Here you don't care what is already in the list as long as it will allow a Thing
to be added; (在这里,您不必关心列表中已有的内容,只要它可以添加Thing
即可。)
this is what ? super Thing
(这是什么? super Thing
)
? super Thing
guarantees. (? super Thing
保证。)