如果要存储MyInterface类型的对象数组,以下是否可以接受,如果使用第一种形式的第二种形式?
i)只使用一个接口: –
- List<MyInterface> mylist = new ArrayList<MyInterface>();
ii)使用通用通配符:
- List<? extends MyInterface> mylist = new ArrayList<? extends MyInterface>();
编辑:
正如迄今为止的答案所指出的,第二号不会编译.我和案例之间有什么区别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>();