2016-06-26 54 views
0

在处理与泛型声明时遇到的声明< ? 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.

所以我的问题是,当我们不能改变的事情与此,那有什么用?只是从该集合中获取元素,如果它是子类型的?

+0

您是否尝试搜索?这一定是以前被问过的。 – Henry

+0

是的,我做了。但没有问题涵盖了我所问的问题,我知道这个通配符的用法,但是我的问题是为什么当我们不能添加/更改现有集合时使用它。 – hellrocker

+0

我没有得到任何编译错误 –

回答

0

这意味着addAll方法允许扩展E类的任何对象集合。 例如,如果G扩展E,则可以向此集合添加一个G数组。

+0

我不认为添加这样的作品。你不能添加这个集合的数组或数组。从技术上讲,通过声明您正在使集合不可变。我是否正确@ marko-topolnik –

+0

我唯一能清楚看到的是从集合类中使用Sort方法。 集合实现静态类。排序是其中的一种语法:public static > void sort(List list)。如果我们不实现Comparable,那么我们不能在这里使用SORT。 –

2

So my question is when we can't modify the thing with this , then what is the use ? Just to get the elements from that collection if it is a subtype ?

是的,这是正确的。只是为了从中获取元素。

请注意,Collection<? extends Number>变量的类型,而不是集合本身的类型。通配符语法的含义更类似于特定集合必须匹配的模式,而不是类似于“对象X是类型T”的类型。

如果Java没有通配符,那么您的表达能力就会受到很大的限制。例如,通用addAll方法将只接受完全相同组件类型的集合。

相关问题