Java泛型中的“超级"和“扩展"有什么区别 [英] What is the difference between 'super' and 'extends' in Java Generics
问题描述
我正在尝试学习 Java 泛型.我不清楚什么时候使用
以及什么时候使用
.这些事情中的每一项对 T 意味着什么?假设我有
和
,它们分别是什么意思?
I am trying to learn Java generics. I am not clear when you will use <T extends Foo>
and when you will use <T super Foo>
. What do each one of these things mean about T? Lets say I have <T extends Comparable>
and <T super Comparable>
, what do each of these mean?
我已经在 sun.com 上阅读了几个教程,但我仍然迷失了方向.有人可以举例说明吗?
I've read several tutorials at sun.com but I'm still lost. Can somebody illustrate with examples?
推荐答案
参见 Effective Java 2nd Edition,Item 28:
See Effective Java 2nd Edition, Item 28:
PECS
Producer extends, Consumer super
Producer extends, Consumer super
如果你的参数是生产者,应该是,如果它是消费者,它必须是
.
If your parameter is a producer, it should be <? extends T>
, if it's a consumer it has to be <? super T>
.
看看 Google Collections,他们知道如何使用它,因为他们有 Bloch ;)
Take a look at the Google Collections, they know how to use it, because they got Bloch ;)
这篇关于Java泛型中的“超级"和“扩展"有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!