在列表中使用通配符时发生编译时错误 [英] compile time error while using wildcard in List
问题描述
List<? extends String> list = new Arraylist<String>();
list.add("foo");
给出一段代码给我编译时错误.我不明白为什么我不能在列表中添加字符串. 但是代码意味着我们可以在列表中添加String类对象及其派生类对象 还是我得到错误的原因
List<?>
仅在您不关心项目的数据类型并且对诸如获取列表大小之类的操作感兴趣的情况下才使用
例如,
public int getSize(List<?> itemList) {
return itemList.size();
}
更多的是Read Only
列表.
如果要列出String
个项目的新列表,则应使用以下内容.
List<String> list = new Arraylist<>();
list.add("foo");
或者,您可以使用此:
List<Object> list = new Arraylist<>();
list.add("foo");
List<? extends String> list = new Arraylist<String>();
list.add("foo");
Given piece of code gives me compile time error.i don't get it why i can't add string in list. but the code means that we can add the String class object and it's derived class object in the list still i am getting the error why
List<?>
should only be used when you are not concerned with the data type of the items and interested in operations such as getting size of list etc.
For Example,
public int getSize(List<?> itemList) {
return itemList.size();
}
It is more of a Read Only
list.
You should be using the following if you intend to make a new list of String
items.
List<String> list = new Arraylist<>();
list.add("foo");
Alternatively, you can use this:
List<Object> list = new Arraylist<>();
list.add("foo");
这篇关于在列表中使用通配符时发生编译时错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!