关于PECS java泛型 [英] regarding PECS java generics

查看:102
本文介绍了关于PECS java泛型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

阅读Java Essentials第2版,在方法参数中有一个叫做PECS的规则来保证类型安全。如果它产生你扩展,消耗你使用超级。



任何人都可以点亮Joshua Bloch指的是生产者/消费者吗?

解决方案

请参阅

泛型类型不变

List< String> 不是的子类型, List< Object>

•适合编译时类型安全,但不灵活

有界通配符类型提供额外的API灵活性
$ b

List< String> 列表与LT ;? extends Object>

List< Object> List的一个子类型? super String>



so


$ b $ p

- Producer extends,Consumer super

•使用 Foo <?为 T 生产者

扩展T>
•使用 Foo<对于 T 消费者



,超级T> 仅适用于输入参数(Don' t使用通配符类型作为返回类型)。

假设您想向堆栈添加批量方法:

  void pushAll(Collection< ;? extends E> src); 
// src是一个E生产者

void popAll(Collection< ;? super E> dst);
// dst是E消费者


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, 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

这篇关于关于PECS java泛型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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