< ;? super E>和<?扩展E>为列表 [英] <? super E> and <? extends E> for List
问题描述
class A {
}
B类扩展A {
}
class C扩展B {
}
我创建了一个ArrayList来保存先前创建的类的对象:
List< ;?延伸A> list1 = new ArrayList< A>();
列表< ;?扩展B> list2 = new ArrayList< B>();
列表< ;?扩展C> list3 = new ArrayList< C>();
列表< ;?超级A> list4 = new ArrayList< A>();
列表< ;? super B> list5 = new ArrayList< B>();
列表< ;? super C> list6 = new ArrayList< C>();
对于每个列表,我试图添加每个早期创建的类的1个对象:A,公元前。唯一可能的组合是:
-
将类A,B,C的对象添加到list4
-
将类B和C的对象添加到list5中
-
将类C的对象添加到列表list6中。
其余的尝试给出编译器错误,比如us:
$ block $
$ block $
($)
不适用于
参数(A)的方法add(捕获#1-of?扩展
A)
为什么我不能将类A,B,C的任何对象添加到list1 / 2/3?
>
为什么例如当list4被定义时,list4接受类A,B,C的对象,如果它们应该是类A的超类,?extends A表示从A(或A本身)派生的某种类型。因此,例如,
List< ByteArrayOutputStream>
与List<扩展OutputStream>
- 但你不应该能够添加一个FileOutputStream
到这样的列表中 - 它应该是一个列表与LT; ByteArrayOutputStream>
!你所知道的是,任何你从获取的东西都会是某种OutputStream
。
?super A是指某种类型是A(或A本身)的超类。因此,例如,
List< OutputStream>
与List<兼容? super ByteArrayOutputStream>
。你肯定可以在这样的列表中添加一个ByteArrayOutputStream
,但是如果你从列表中获取一个项目,你不能真正保证太多。
请参阅 Angelika Langer的泛型常见问题解答获取更多信息。
Having the following simple class structure:
class A { } class B extends A { } class C extends B { }
I'm creating an ArrayList to keep objects of the earlier created classes:
List<? extends A> list1 = new ArrayList<A>(); List<? extends B> list2 = new ArrayList<B>(); List<? extends C> list3 = new ArrayList<C>(); List<? super A> list4 = new ArrayList<A>(); List<? super B> list5 = new ArrayList<B>(); List<? super C> list6 = new ArrayList<C>();
To each of those lists I'm trying to add 1 object of each earlier created class: A,B,C. The only possible combination is:
adding object of class A,B,C to list4
adding object of class B and C to list5
adding object of class C to list list6. The rest of the tries gives compiler errors, such us:
The method add(capture#1-of ? extends A) in the type List is not applicable for the arguments (A)
Why can't I add any object of class A,B,C to list1/2/3? Why e.g. list4 accepts objects of classes A,B,C if they are supposed to be a super class of class A, as the list4 is defined?
解决方案"? extends A" means "some type derived from A (or A itself)". So for instance, a
List<ByteArrayOutputStream>
is compatible withList<? extends OutputStream>
- but you shouldn't be able to add aFileOutputStream
to such a list - it's meant to be aList<ByteArrayOutputStream>
! All you know is that anything you fetch from the list will be anOutputStream
of some kind."? super A" means "some type which is a superclass of A (or A itself)". So for instance, a
List<OutputStream>
is compatible withList<? super ByteArrayOutputStream>
. You can definitely add aByteArrayOutputStream
to such a list - but if you fetch an item from the list, you can't really guarantee much about it.See Angelika Langer's Generics FAQ for much more information.
这篇关于< ;? super E>和<?扩展E>为列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!