简体   繁体   中英

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>

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>

Your process method needs to return an implementation of the interface List. This could as well be something incompatible to ArrayList, eg. a LinkedList. The compiler notices that and forbids it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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