下面的代码:
List<? extends String> genericNames = new ArrayList<String>();
genericNames.add("John");
给出编译器错误:
Multiple markers at this line - The method add(capture#1-of ? extends String) in the type List is not applicable for the arguments (String) - The method add(capture#1-of ?) in the type List is not applicable for the arguments (String)
是什么导致了这个错误?由于我在类型参数中扩展了 String,我是否应该无法添加字符串或其子类型?
最佳答案
当您在扩展中使用通配符时,您无法在集合中添加除 null 之外的任何内容。另外,String 是最后一个类;没有任何东西可以扩展字符串。
原因:如果允许,您可能只是将错误的类型添加到集合中。
示例:
class Animal {
}
class Dog extends Animal {
}
class Cat extends Animal {
}
现在你有List<? extends Animal>
public static void someMethod(List<? extends Animal> list){
list.add(new Dog()); //not valid
}
然后您像这样调用该方法:
List<Cat> catList = new ArrayList<Cat>();
someMethod(catList);
如果在使用带有扩展的通配符时允许添加到集合中,则您只需将 Dog 添加到仅接受 Cat 或子类型类型的集合中。因此,您无法将任何内容添加到使用具有上限的通配符的集合中。
关于java - 通过使用通用 'extends' 添加字符串会导致编译器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13993745/