繁体   English   中英

Java中具有通用集合的多态

[英]Polymorphism with generic collections in Java

给定此方法:

public static <E extends Number> List<E> process(List<E> num)

我想做这个 :

ArrayList<Integer> input = null ;
ArrayList<Integer> output = null ;

output = process(input);

我遇到异常:类型不匹配:无法从List<Integer>转换为ArrayList<Integer>

我知道我可以做些正确的事情:

List<Integer> list = new ArrayList<Integer>;

为什么在这里不起作用?

问题是返回类型。 process()返回一个List<E>而您正在尝试将其填充到ArrayList<E>

您的处理方法需要返回接口List的实现。 例如,这也可能与ArrayList不兼容。 一个LinkedList。 编译器会注意到并禁止它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM