问题描述
我正在学习Java泛型。我不清楚何时使用< T extends Foo>
,以及何时使用< T super Foo>
。这些东西对T来说意味着什么?假设我有< T扩展Comparable>
和< T super Comparable>
,这些都意味着什么?
我已经在sun.com上看过几篇教程,但我仍然迷失。有人可以举例说明吗?
谢谢!
Java第2版,第28项:
PECS
/ strong> 是生产者,它应该是<?扩展T>
,如果它是一个消费者,它必须是<?看看Google Collections,他们知道如何使用它,因为他们得到了Bloch;)
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?
I've read several tutorials at sun.com but I'm still lost. Can somebody illustrate with examples?
Thanks!
See Effective Java 2nd Edition, Item 28:
PECS
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>
.
Take a look at the Google Collections, they know how to use it, because they got Bloch ;)
这篇关于Java泛型中'super'和'extends'有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!