在处理与泛型声明时遇到的声明< ? extends E>
。 如果我以集合接口的addAll方法为例。什么是<?扩展E>
它的声明是这样的:
interface Collection<E> {
public boolean addAll(Collection<? extends E> c);
}
从中的addAll上述声明我所了解(从不同的来源读取)
使
? extends E
意味着它也OK添加具有任何类型元素的所有成员都是E的子类型
让我们来看看这个例子:
List<Integer> ints = new ArrayList<Integer>();
ints.add(1);
ints.add(2);
List<? extends Number> nums = ints; // now this line works
/*
*without using ? syntax above line did not use to compile earlier
*/
List<Double> doubleList = new ArrayList<Double>();
doubleList.add(1.0);
nums.addall(doubleList); // compile time error
错误:
The method addall(List< Double >) is undefined for the type List< capture#1-of ? extends Number >
我也看了在O'Reilly的 'Java泛型和集合'
In general, if a structure contains elements with a type of the form ? extends E, we can get elements out of the structure, but we cannot put elements into the structure.
所以我的问题是,当我们不能改变的事情与此,那有什么用?只是从该集合中获取元素,如果它是子类型的?
您是否尝试搜索?这一定是以前被问过的。 – Henry
是的,我做了。但没有问题涵盖了我所问的问题,我知道这个通配符的用法,但是我的问题是为什么当我们不能添加/更改现有集合时使用它。 – hellrocker
我没有得到任何编译错误 –