如果要存储类型为MyInterface的对象数组,则以下两种方法均可接受,如果可以,何时在第一种形式上使用第二种形式?

i)仅使用接口(interface):

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

ii)使用通用通配符:
List<? extends MyInterface> mylist = new ArrayList<? extends MyInterface>();

编辑:

正如到目前为止的答案所指出的,ii号不会编译。 i和情况iii之间有什么区别:

iii)仅在引用文献中使用通用通配符:
List<? extends MyInterface> mylist = new ArrayList<MyInterface>();

最佳答案

第二个不会编译。想象:

A implements MyInterface
B implements MyInterface

然后,以下内容将与您的第二个表达式匹配,但不会编译:
// incorrect
List<A> mylist = new ArrayList<B>();

更正:也错了:
List<? extends MyInterface> mylist = new ArrayList<MyInterface>();

从某种意义上说它确实可以编译,但是您不能向其中添加MyInterface的任何子类。令人困惑,但正确-在我阅读了说明之后。相同的原因:通配符可以例如查看为:
// 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>();

所以这行不通:
mylist.add(b);

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

该选项允许您将MyInterface的任何子类添加到mylist中:
List<MyInterface> mylist = new ArrayList<MyInterface>();

10-08 19:36