Reputation: 10961
Why won't the following code compile?
public static <T> void foo_test(List<? extends T> src, List<T> dest) {
for (T o : src) {
dest.add(o);
}
}
public static void main(String [] args) {
List<Number> numbers = new ArrayList<Number>();
List<Integer> integers = new ArrayList<Integer>();
foo_test(numbers, integers);
}
Upvotes: 1
Views: 50
Reputation: 14257
You need to switch integers
and numbers
. The src
list has to be the more specific type than dest
.
Upvotes: 1
Reputation: 178263
You shouldn't and can't add the list of numbers to a list of integers; the numbers may not be integers. However, you can add a list of integers to a list of numbers, the backwards of what you've typed.
This will work:
foo_test(integers, numbers);
To elaborate, T
is inferred as Integer
in your code, but Number
doesn't extend Integer
, so the call is a compiler error.
Switching to foo_test(integers, numbers)
makes T
inferred as Number
, and Integer
does extend Number
, so that compiles.
Upvotes: 5