leonidas79
leonidas79

Reputation: 469

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 ?

Upvotes: 0

Views: 141

Answers (2)

sorencito
sorencito

Reputation: 2625

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.

Upvotes: 0

sshannin
sshannin

Reputation: 2825

The problem is the return type. process() returns a List<E> and you're trying to stuff that into an ArrayList<E>

Upvotes: 4

Related Questions