简体   繁体   中英

wildcard type matching - Java

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);
}

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.

You need to switch integers and numbers . The src list has to be the more specific type than dest .

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