使用通用通配符而不是接口 [英] Use of generic wildcard instead of interface

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

问题描述

如果您想存储 MyInterface 类型的对象数组,下列两个都可以接受,如果是这样,您何时会使用第二种形式?

<$ p
$ b

i) mylist = new ArrayList< MyInterface>();



使用通用通配符: - $ /

 列表与LT ;?扩展MyInterface> mylist = new ArrayList <?扩展MyInterface>(); 

编辑:

远远指出,数字ii不会编译。我和一个案例之间有什么区别iii其中: -



iii)仅在引用中使用通用通配符: -

 列表< ;?扩展MyInterface> mylist = new ArrayList< MyInterface>(); 


解决方案

第二个不会编译。想象一下:

  A实现MyInterface 
实现MyInterface

然后下面的代码会匹配你的第二个表达式,但不会编译:

  //不正确
列表< A> mylist = new ArrayList< B>();

更正:错误也是

 列表< ;?扩展MyInterface> mylist = new ArrayList< MyInterface>(); 

从某种意义上讲,它是编译的,但是不能将MyInterface的任何子类添加到它。我读了解释后感到困惑,但是正确。相同的原因:通配符可以被视为例如:

  //我知道这是不可编译的;这是内部编译器思考。 
//将它读为某处某人可以实例化一个ArrayList< A>并将
//传递给我们;但我们不能接受它作为可能是
//可能使用的东西作为列表< B>
列表< A> mylist = new ArrayList< MyInterface>();

所以这是行不通的:

  mylist.add(b); 

,反之亦然。编译器拒绝执行那些可能不正确的操作。



允许您将MyInterface的任何子类添加到mylist的选项为:

 列表< MyInterface> mylist = new ArrayList< MyInterface>(); 


If you wanted to store an array of objects of type MyInterface, are the following both acceptable and if so when would you use the second form over the first?

i) Using only an interface:-

List<MyInterface> mylist = new ArrayList<MyInterface>();

ii) Using a generic wildcard:-

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

Edit:

As the answers so far have pointed out, number ii won't compile. What is the difference between i and a case iii where :-

iii) Using a generic wildcard only in the reference:-

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

解决方案

Second one won't compile. Imagine:

A implements MyInterface
B implements MyInterface

Then the following would match your second expression, but won't compile:

// incorrect
List<A> mylist = new ArrayList<B>();

Correction: Wrong one too:

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

It is right in a sense it does compile, but you cannot add any subclasses of MyInterface to it. Confusing, but correct -- after I read the explanation. Same reason: wildcard can be viewed for example as:

// I know this is not compileable; this is internal compiler "thinking".
// Read it as "somewhere someone may instantiate an ArrayList<A> and pass 
// it down to us; but we cannot accept it as something that could be 
// potentially used as List<B>"
List<A> mylist = new ArrayList<MyInterface>();

So this won't work:

mylist.add(b);

and vice versa. Compiler refuses to do those potentially incorrect operations.

The option which allows you to add any subclass of MyInterface to mylist is:

List<MyInterface> mylist = new ArrayList<MyInterface>();

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

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