通过使用泛型'extends'添加字符串会导致编译器错误

blu*_*sky 0 java

代码如下:

List<? extends String> genericNames = new ArrayList<String>();
genericNames.add("John");
Run Code Online (Sandbox Code Playgroud)

给编译器错误:

此行中的多个标记 - 类型List中的方法add(capture#1-of?extends String)不适用于参数(String) - 类型List中的方法add(capture#1-of?)不是适用于参数(String)

导致此错误的原因是什么?我是否应该无法添加字符串或其子类型,因为我在类型参数中扩展String?

Per*_*ror 10

将通配符与extends一起使用时,除了null之外,不能在集合中添加任何内容.另外,String是最后一个类; 没有什么可以扩展String.

原因:如果允许,您可以将错误的类型添加到集合中.

例:

class Animal {

}

class Dog extends Animal {

}

class Cat extends Animal {

}
Run Code Online (Sandbox Code Playgroud)

现在你有了 List<? extends Animal>

public static void someMethod(List<? extends Animal> list){
    list.add(new Dog()); //not valid
}
Run Code Online (Sandbox Code Playgroud)

你调用这样的方法:

List<Cat> catList = new ArrayList<Cat>(); 
someMethod(catList);
Run Code Online (Sandbox Code Playgroud)

如果在使用带扩展名的通配符时允许添加集合,则只需将Dog添加到仅接受Cat或子类型类型的集合中.因此,您无法在使用带上限的通配符的集合中添加任何内容.