简体   繁体   English

通配符类型匹配-Java

[英]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. 详细地说, T在您的代码中被推断为Integer ,但是Number并没有扩展Integer ,因此该调用是编译器错误。

Switching to foo_test(integers, numbers) makes T inferred as Number , and Integer does extend Number , so that compiles. 切换到foo_test(integers, numbers)可以将T推断为Number ,并且Integer确实扩展Number ,以便进行编译。

You need to switch integers and numbers . 您需要切换integersnumbers The src list has to be the more specific type than dest . src列表必须是比dest更具体的类型。

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

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