问题描述
我有一些关于集合中使用的通用通配符符号(反直觉)的观察。
通配符表达式的目的 List 扩展T>
是允许List(T的子类型)的赋值给List的引用。的T'。其目的不是特别允许将T的子类型的元素添加到列表中('T'的列表),即使在 List< T>
。
列表<号码> list = new ArrayList< Integer>(); //无效,List< Integer>不能分配给List< Number>
列表<号码> list = new ArrayList< Number>(); // OK
list.add(new Integer(1)); //有效,'?扩展数字'不需要!
列表< ;?扩展Number> list1 = new ArrayList< Integer>(); //有效,因为符号'?扩展数字'
我的观察是否正确?
是的,你的观察是正确的。但是,在你展示的情况下,它不是非常有用(你选择忽略关于列表的有用信息)。例如,假设你有一个库函数关闭了InputStreams的集合,那么这个赋值在你调用一个库函数的时候是隐含的,它是非常有用的。 您可以接受 List< InputStream>
,但这是不必要的限制。你可以这样做:
public void closeAll(Collection< ;? extends InputStream> streams){
for(InputStream stream:streams){
stream.close();
$ b现在你可以传入一个列出< FileInputStream>
代替。
I have this bit of ( counter-intuitive ) observations about generic wildcard notation used in collections.
The purpose of the wildcard notation List<? extends T>
is to allow the assignment of a List (of subtypes of T) to the reference of List of '? of T'. Its purpose is not to specifically allow the adding of elements of subtypes of T into the List ( of '? of T' ) , which is possible even in a List<T>
.
List<Number> list = new ArrayList<Integer>(); // invalid , List<Integer> is not assignable to List<Number>
List<Number> list = new ArrayList<Number>() ; // OK
list.add(new Integer(1)); // valid , '? extends Number' not needed!
List<? extends Number> list1 = new ArrayList<Integer>(); // Valid , because of notation '? extends Number'
Is my observation correct ?
解决方案 Yes, your observation is correct. However, in the case you show, it's not very useful (you're electing to ignore useful information about the list). The assignment is more useful when it's implicit as you call a library function.
For example, say you had a library function that closed a collection of InputStreams. You could accept a List<InputStream>
, but that is unnecessarily restrictive. You could instead do this:
public void closeAll(Collection<? extends InputStream> streams) {
for ( InputStream stream : streams ) {
stream.close();
}
}
Now you can pass in a List<FileInputStream>
instead.
这篇关于通配符的主要用途或目的'?延长T'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!