【发布时间】:2015-11-07 18:19:56
【问题描述】:
我有以下Java 类定义:
import java.util.*;
public class Test {
static public void copyTo(Iterator<? extends Number> it, List<? extends Number> out) {
while(it.hasNext())
out.add(it.next());
}
public static void main(String[] args) {
List<Integer> in = new ArrayList<Integer>();
for (int i = 1; i <= 3; i++) {
in.add(i);
}
Iterator<Integer> it = in.iterator();
List<Number> out = new ArrayList<Number>();
copyTo(it, out);
System.out.println(out.size());
}
}
就是这样,我在Java 中使用wildcards 定义了方法copyTo。我定义List<Number> out 但Iterator<Integer> it。我的想法是我可以将迭代器定义为 Iterator<? extends Number> 并且类型匹配。然而事实并非如此:
Test.java:13: error: no suitable method found for add(Number)
out.add(it.next());
^
method List.add(int,CAP#1) is not applicable
(actual and formal argument lists differ in length)
method List.add(CAP#1) is not applicable
(actual argument Number cannot be converted to CAP#1 by method invocation conversion)
method Collection.add(CAP#1) is not applicable
(actual argument Number cannot be converted to CAP#1 by method invocation conversion)
where CAP#1 is a fresh type-variable:
CAP#1 extends Number from capture of ? extends Number
1 error
所以我继续为copyTo 方法定义了另一个定义:
static public void copyTo(Iterator<? super Integer> it, List<? super Integer> out) {
while(it.hasNext())
out.add(it.next());
}
它也不起作用。在这种情况下使用wildcards 的正确说法是什么?
【问题讨论】:
标签: java templates generics types wildcard