通过使用泛型'extends'添加字符串会导致编译器错误 [英] Add Strings through use of generic 'extends' causes compiler error

查看:75
本文介绍了通过使用泛型'extends'添加字符串会导致编译器错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码如下:

List<? extends String> genericNames = new ArrayList<String>();
genericNames.add("John");

给出编译错误:


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

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?

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'添加字符串会导致编译器错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆