Java – use generic wildcards instead of interfaces
•
Java
If you want to store an array of objects of type myinterface, is it acceptable to use the second form of the first form?
i) Use only one interface: –
List<MyInterface> mylist = new ArrayList<MyInterface>();@H_403_5@ii)使用通用通配符:
List<? extends MyInterface> mylist = new ArrayList<? extends MyInterface>();@H_403_5@编辑:
正如迄今为止的答案所指出的,第二号不会编译.我和案例之间有什么区别iii其中:
iii)仅在引用中使用通配符: –
List<? extends MyInterface> mylist = new ArrayList<MyInterface>();@H_403_5@Solution
The second will not compile Imagine:
A implements MyInterface B implements MyInterface@H_403_5@那么以下将匹配您的第二个表达式,但不会编译:
// incorrect List<A> mylist = new ArrayList<B>();@H_403_5@更正错误:
List<? extends MyInterface> mylist = new ArrayList<MyInterface>();@H_403_5@在某种意义上说它是编译的,但是你不能添加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>();@H_403_5@所以这不行:
mylist.add(b);@H_403_5@反之亦然.编译器拒绝做这些可能不正确的操作.
允许您将MyInterface的任何子类添加到mylist的选项是:
List<MyInterface> mylist = new ArrayList<MyInterface>();@H_403_5@
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码