什么是 PECS(生产者扩展消费者超级)? [英] What is PECS (Producer Extends Consumer Super)?

查看:32
本文介绍了什么是 PECS(生产者扩展消费者超级)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在阅读泛型时遇到了 PECS(Producer extends 和 Consumer super 的缩写).

I came across PECS (short for Producer extends and Consumer super) while reading up on generics.

谁能向我解释一下如何使用 PECS 来解决 extendssuper 之间的混淆?

Can someone explain to me how to use PECS to resolve confusion between extends and super?

推荐答案

tl;dr:是从集合的角度来看.如果你从一个泛型集合中提取项目,它是一个生产者,你应该使用extends;如果你往里面塞东西,它就是一个消费者,你应该使用super.如果您使用相同的集合同时执行这两项操作,则不应使用 extendssuper.

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 添加任何内容(除了 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆