Java中泛型集合的多态性
鉴于此方法:Java中泛型集合的多态性,java,generics,collections,polymorphism,Java,Generics,Collections,Polymorphism,鉴于此方法: public static <E extends Number> List<E> process(List<E> num) 公共静态列表进程(List num) 我想这样做: ArrayList<Integer> input = null ; ArrayList<Integer> output = null ; output = process(input); ArrayList输入=null; ArrayList
public static <E extends Number> List<E> process(List<E> num)
公共静态列表进程(List num)
我想这样做:
ArrayList<Integer> input = null ;
ArrayList<Integer> output = null ;
output = process(input);
ArrayList输入=null;
ArrayList输出=null;
输出=过程(输入);
我得到一个异常:类型不匹配:无法从List
转换到ArrayList
我知道我可以得到这样正确的东西:
List<Integer> list = new ArrayList<Integer>;
List List=newarraylist;
为什么它在这里不起作用?问题在于返回类型
process()
返回一个列表
,您试图将其填充到数组列表中
问题在于返回类型process()
返回一个列表
,您试图将其填充到数组列表中
您的流程方法需要返回接口列表的实现。这也可能与ArrayList不兼容,例如LinkedList。编译器注意到并禁止它。您的进程方法需要返回接口列表的实现。这也可能与ArrayList不兼容,例如LinkedList。编译器注意到并禁止它。process
可能返回一个LinkedList
,它不是ArrayList
的子类型。process
也可能返回一个LinkedList
的子类型,它不是ArrayList
的子类型。对于您的答案,您的解释是逻辑,我现在明白了。对于你的回答,你的解释是合乎逻辑的,我现在明白了