关于PECS java泛型 [英] regarding PECS java generics
问题描述
任何人都可以点亮Joshua Bloch指的是生产者/消费者吗?
请参阅 泛型类型不变 有界通配符类型提供额外的API灵活性 • so - Producer extends,Consumer super •使用 ,超级T> 仅适用于输入参数(Don' t使用通配符类型作为返回类型)。 假设您想向堆栈添加批量方法: Reading Java Essentials, 2nd edition, there's a rule called PECS for type safety 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, Bounded wildcard types provide additional API flexibilty • so PECS — Producer extends, Consumer super • use only applies to input parameters (Don’t use wildcard types as return types). Suppose you want to add bulk methods to Stack:
这篇关于关于PECS java泛型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
的子类型, List< Object>
•适合编译时类型安全,但不灵活
$ b List< String>
是列表与LT ;? extends Object>
• List< Object>
是 List的一个子类型? super String>
$ b $ p
Foo <?为
•使用 T
生产者
扩展T> Foo<对于
T
消费者
void pushAll(Collection< ;? extends E> src);
// src是一个E生产者
void popAll(Collection< ;? super E> dst);
// dst是E消费者
List<String>
is not a subtype of List<Object>
• Good for compile-time type safety, but inflexible List<String>
is a subtype of List<? extends Object>
• List<Object>
is a subtype of List<? super String>
Foo<? extends T>
for a T
producer
• use Foo<? super T>
for a T
consumervoid pushAll(Collection<? extends E> src);
//src is an E producer
void popAll(Collection<? super E> dst);
// dst is an E consumer