如何将元素添加到通配符泛型集合中? [英] How can elements be added to a wildcard generic collection?

查看:109
本文介绍了如何将元素添加到通配符泛型集合中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  1 public List <?> 

延伸Foo> getFoos()
2 {
3列表< ;?延伸Foo> foos =新的ArrayList <?扩展Foo>();
4 foos.add(new SubFoo());
5返回foos;
6}

其中'SubFoo'是一个实现Foo的具体类,而Foo是一个接口。 / p>

使用此代码得到的错误:


  • 在线3:无法实例化第4行:类型List< capture#1-of?extends Foo>中的方法add(capture#1 of?extends Foo)><不适用于参数(SubFoo)



更新:感谢Jeff C,我可以改变第3行说新的ArrayList< Foo>();。但是我仍然遇到了第4行的问题。

解决方案

使用此代替:

  1公开清单<?延伸Foo> getFoos()
2 {
3 List< Foo> foos = new ArrayList< Foo>(); / *或列表< SubFoo> * /
4 foos.add(new SubFoo());
5返回foos;
6

一旦你声明foos为 List<扩展Foo> ,编译器不知道添加SubFoo是安全的。如果 ArrayList< AltFoo> 已被分配给 foos ,该怎么办?这将是一个有效的任务,但添加一个SubFoo会污染该集合。


Why do I get compiler errors with this Java code?

1  public List<? extends Foo> getFoos()
2  {
3    List<? extends Foo> foos = new ArrayList<? extends Foo>();
4    foos.add(new SubFoo());
5    return foos;
6  }

Where 'SubFoo' is a concrete class that implements Foo, and Foo is an interface.

Errors I get with this code:

  • On Line 3: "Cannot instantiate ArrayList<? extends Foo>"
  • On Line 4: "The method add(capture#1-of ? extends Foo) in the type List<capture#1-of ? extends Foo> is not applicable for the arguments (SubFoo)"

Update: Thanks to Jeff C, I can change Line 3 to say "new ArrayList<Foo>();". But I'm still having the issue with Line 4.

解决方案

Use this instead:

1  public List<? extends Foo> getFoos()
2  {
3    List<Foo> foos = new ArrayList<Foo>(); /* Or List<SubFoo> */
4    foos.add(new SubFoo());
5    return foos;
6  }

Once you declare foos as List<? extends Foo>, the compiler doesn't know that it's safe to add a SubFoo. What if an ArrayList<AltFoo> had been assigned to foos? That would be a valid assignment, but adding a SubFoo would pollute the collection.

这篇关于如何将元素添加到通配符泛型集合中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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