【发布时间】:2014-02-05 10:31:35
【问题描述】:
考虑以下代码:
class Super {}
class Sub extends Super {}
class Test {
public static void main(String[] args) {
List<? extends Super> list = new ArrayList<Sub>(); //1
list.add(new Sub()); //2
}
}
第一行编译成功,第二行编译失败:
The method add(capture#2-of ? extends Super) in the type List<capture#2-of ? extends Super> is not applicable for the arguments (Sub)
我的问题是:
1)为什么第1行编译成功?
2) 第 1 行是声明列表(或其他集合)的好习惯吗?
3) 为什么在第 1 行声明 list 为 Sub 类型后,第 2 行编译失败?
4) Eclipse 的自动完成功能说现在列表中只允许“空”元素。为什么?
非常感谢!
【问题讨论】:
标签: java generics arraylist wildcard