java – 使用通用通配符代替接口
发布时间:2020-12-14 05:22:44 所属栏目:Java 来源:网络整理
导读:如果要存储MyInterface类型的对象数组,以下是否可以接受,如果使用第一种形式的第二种形式? i)只使用一个接口: – ListMyInterface mylist = new ArrayListMyInterface(); ii)使用通用通配符: List? extends MyInterface mylist = new ArrayList? extends
如果要存储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>(); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |