在列表中使用通配符时发生编译时错误 [英] compile time error while using wildcard in List

查看:72
本文介绍了在列表中使用通配符时发生编译时错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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屋!

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