问题描述
代码如下:
List<? extends String> genericNames = new ArrayList<String>();
genericNames.add("John");
给出编译错误:
导致什么原因这个错误?我是否应该无法添加字符串或其子类型,因为我在类型参数中扩展String?
What is causing this error ? Should I not be able to add Strings or its subtype since I am extending String within the type parameter ?
推荐答案
当您使用通配符时使用extends,除了 null 之外,您无法在集合中添加任何内容。另外,String是最后一个类;没有什么可以扩展字符串。
When you use wildcards with extends, you can't add anything in the collection except null. Also, String is a final class; nothing can extend String.
原因:如果允许,你可能只是在集合中添加了错误的类型。
Reason: If it were allowed, you could just be adding the wrong type into the collection.
示例:
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或子类型的集合。因此,您无法在使用带有上限的通配符的集合中添加任何内容。
If it were allowed to add in the collection when using wildcards with extends, you just added a Dog into a collection which accepts only Cat or subtype type. Thus you can't add anything into the collection which uses wildcards with upper bounds.
这篇关于通过使用泛型'extends'添加字符串会导致编译器错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!