开发者

regarding PECS java generics

Reading Java Essentials, 2nd edition, there's a rule called PECS for type safe开发者_如何学运维ty in method parameters. If it produces you extend, consumes you use super. Sorry if I defined it wrong as I don't get it.

Can anyone shed light on what Joshua Bloch is referring to as the producer/consumer?


See this pdf which has a series of slides on this (search for PECS):

Generic types are invariant

• That is, List<String> is not a subtype of List<Object>
• Good for compile-time type safety, but inflexible

Bounded wildcard types provide additional API flexibilty

List<String> is a subtype of List<? extends Object>
List<Object> is a subtype of List<? super String>

so

PECSProducer extends, Consumer super

• use Foo<? extends T> for a T producer
• use Foo<? super T> for a T consumer

only applies to input parameters (Don’t use wildcard types as return types).

Suppose you want to add bulk methods to Stack:

void pushAll(Collection<? extends E> src);
//src is an E producer

void popAll(Collection<? super E> dst);
// dst is an E consumer


When a method reads/iterates over elements in a collection then it is a consumer, when it ads to a collections then it is a producer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜