我使用下面的代码,并试着添加子对象名单:Java的泛型类型的通配符扩展允许添加仅空
List<? extends Parent> list = new ArrayList<Child>();
list.add(new Child()); //error: The method add(capture#1-of ? extends Parent) in the type List<capture#1-of ? extends Parent> is not applicable for the arguments (Child)
class Parent{
}
class Child extends Parent{
}
我想知道为什么这里的编译器错误抛出?
如果你想解决,替换'List <?将Parent>'扩展为'列表'。如果你想了解谷歌协变和逆变。 –
talex
2014-09-02 09:11:44
为什么要将'list'的类型声明为'List <?如果你不知道它是什么意思,那么扩展Parent>'如果你创建一个'ArrayList'你为什么不把它保存为'List '? –
Holger
2014-09-02 09:29:19
*为什么要将列表的类型声明为List <?如果你不知道它是什么意思,那么扩展Parent> *,@Holger,这就是人们如何学习,通过做事情:) – sanbhat 2014-09-02 09:37:20