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

标签 java

下面的代码:

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/

相关文章:

java - 我需要什么类型的图像处理才能使 OpenCV 的图像清晰?

java - 如何在 Java 中创建 Kafka ZKStringSerializer?

hibernate - 如何在序列化过程中限制hibernate相关对象

java - Spring MVC weblogic ClassNotFoundException

java - 如何在 IntelliJ 中使用 maven-ear-plugin 的 bundleFileName?

java - Android - Blogger(最佳身份验证方法 - ClientLogin 等)

java - spring data jpa 过滤 @OneToMany 中的子级

java - 如何在 Spring Boot、JPA、Spring Security 中将表单登录扩展到 Google Sign in (OAuth2)

java - Hibernate (JPA) 多个@OneToMany 用于同一模型

java - 如何在不使用循环结构的情况下遍历 ArrayList?