使用通配符的Java集合 [英] Java Collections using wildcard

查看:83
本文介绍了使用通配符的Java集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public static void main(String[] args) {

    List<? extends Object> mylist = new ArrayList<Object>();

    mylist.add("Java"); // compile error

}

以上代码不允许你将元素添加到列表中,通配符只能用作方法中的签名,同样不能用于添加,而只能用于访问。
在这种情况下,上述目的是什么?

The above code does not allow you to add elements to the list and wild cards can only be used as a signature in methods, again not for adding but only for accessing. In this case what purpose does the above fulfil ??

推荐答案

假设你有一个接口和两个类:

Let's say you have an interface and two classes:

interface IResult {}
class AResult implements IResult {}
class BResult implements IResult {}

然后你的类会返回一个列表:

Then you have classes that return a list as a result:

interface ITest<T extends IResult> {
  List<T> getResult();
}

class ATest implements ITest<AResult> {
  // look, overridden!
  List<AResult> getResult();
}

class BTest implements ITest<BResult> {
  // overridden again!
  List<BResult> getResult();
}

这是一个很好的解决方案,当你需要协变回报,但你返回集合而不是您自己的对象。最重要的是,当您独立于ITest界面使用ATest和BTest时,您不必投射对象。但是,在使用ITest界面时,您无法向返回的列表添加任何内容 - 因为您无法确定列表实际包含的对象类型!如果允许,您可以将BResult添加到List< AResult> (以List<?延伸T>返回),这没有任何意义。

It's a good solution, when you need "covariant returns", but you return collections instead of your own objects. The big plus is that you don't have to cast objects when using ATest and BTest independently from the ITest interface. However, when using ITest interface, you cannot add anything to the list that was returned - as you cannot determine, what object types the list really contains! If it would be allowed, you would be able to add BResult to List<AResult> (returned as List<? extends T>), which doesn't make any sense.

所以你必须记住这一点:List<?扩展X>定义一个可以轻松覆盖的列表,但该列表是只读的。

So you have to remember this: List<? extends X> defines a list that could be easily overridden, but which is read-only.

这篇关于使用通配符的Java集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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