[英]Generics extends and super with ? differencies
I try to understand generics behaviour in java 我试图了解Java中的泛型行为
I write same code: 我写同样的代码:
common part: 共同部分:
class A1{}
class B1 extends A1{}
class C1 extends B1{}
case 1: 情况1:
List<? extends B1> list = new ArrayList<C1>();
list.add(new A1());// compile error
list.add(new B1());//compile error
list.add(new C1());//compile error
case 2: 情况2:
List<? super B1> list = new ArrayList<A1>();
list.add(new A1());//compile error
list.add(new B1());//valid
list.add(new C1());//valid
I think that I wrote simmetrical code. 我认为我写了模拟代码。 Why I see non-simmetrical results? 为什么我看到非对称结果?
List<? extends B1>
List<? extends B1>
means: a list of an unknow type, which is or extends B1. List<? extends B1>
表示:一个未知类型的列表,它是B1或扩展为B1。 So it could be a List<B1>
, a List<C1>
, or a List<Foo>
if Foo
also extends B1
or C1
. 因此,如果Foo
还扩展了B1
或C1
,则它可以是List<B1>
, List<C1>
或List<Foo>
。 So you can't add anything to such a list: 因此,您无法在此列表中添加任何内容:
list.add(new A1); // incorrect, since A1 doesn't even extend B1
list.add(new B1()); // incorrect, since the list could be a List<C1>
list.add(new C1()); // incorrect, since the list could be a List<Foo>
The only thing you can add to such a list is null. 您可以添加到此类列表的唯一内容是null。
List<? super B1>
List<? super B1>
means: a list of an unknow type, which is B1 or a superclass or superinterface of B1
. List<? super B1>
意味着:一个不明类型,这是B1或一个超类或超列表B1
。 So it could be a List<B1>
, a List<A1>
, or a List<Object>
(and nothing else). 因此它可以是List<B1>
, List<A1>
或List<Object>
(仅此而已)。 So 所以
list.add(new A1()); // incorrect, since the list could be a List<B1>, and A1 is not a B1
list.add(new B1()); // valid, since whatever the type of the list (B1, A1 or Object), B1 is of this type
list.add(new C1()); // valid, since whatever the type of the list (B1, A1 or Object), B1 is of this type
If you try to get an element from such a list, though, you can't have any guarantee about its type. 但是,如果尝试从此类列表中获取元素,则不能保证其类型。 The only sure thing is that it's an Object. 唯一可以确定的是它是一个对象。
The general principle is PECS: Producer Extends, Consumer Super. 一般原则是PECS:生产者扩展,消费者超级。 This means that when a list is a producer (which means you want to get elements from it), then extends
should be used. 这意味着当列表是生产者时(这意味着您要从中获取元素),则应使用extends
。 When the list is a consumer (which means you want to add elements to it), then super
should be used. 当列表是使用者时(这意味着您要向其中添加元素),则应使用super
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.