简体   繁体   English

Java中具有通用集合的多态

[英]Polymorphism with generic collections in Java

Given this method: 给定此方法:

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

I want to do this : 我想做这个 :

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

output = process(input);

I get an exception : Type mismatch: cannot convert from List<Integer> to ArrayList<Integer> 我遇到异常:类型不匹配:无法从List<Integer>转换为ArrayList<Integer>

I know that I can have something correct like that : 我知道我可以做些正确的事情:

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

Why doesn't it work here ? 为什么在这里不起作用?

The problem is the return type. 问题是返回类型。 process() returns a List<E> and you're trying to stuff that into an ArrayList<E> process()返回一个List<E>而您正在尝试将其填充到ArrayList<E>

Your process method needs to return an implementation of the interface List. 您的处理方法需要返回接口List的实现。 This could as well be something incompatible to ArrayList, eg. 例如,这也可能与ArrayList不兼容。 a LinkedList. 一个LinkedList。 The compiler notices that and forbids it. 编译器会注意到并禁止它。

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

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