在一个项目中,我希望用List泛型通配符来add数据,不过出错了。请那位大虾给小弟说说这个List的通配符可不可这样做。谢谢
public class test {
private static List<? extends Object> list;
public static void main(String[] args) {
list = new ArrayList<String>();
list.add("aaa");
list.get(1);
}
}
提示如下
Severity and Description Path Resource Location Creation Time Id
The method add(capture#2-of ?) in the type List<capture#2-of ?> is not applicable for the arguments (String) test.java line 10 1200313007390 6736
public class test {
private static List<? extends Object> list;
public static void main(String[] args) {
list = new ArrayList<String>();
list.add("aaa");
list.get(1);
}
}
提示如下
Severity and Description Path Resource Location Creation Time Id
The method add(capture#2-of ?) in the type List<capture#2-of ?> is not applicable for the arguments (String) test.java line 10 1200313007390 6736
这是我的解决办法...public void add(int index, Object element) {
if (element instanceof Test) {
Test new_name = (Test) element;
}else{
//可以抛出一个异常
return ;
}
super.add(index, element);
}@Override
public boolean add(Object o) {
if (o instanceof Test) {
Test new_name = (Test) o;
}else{
//可以抛出一个异常
return false;
}
return super.add(o);
}
希望能有用,继续关注