我有以下Java
类定义: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
的正确说法是什么?
如果它是'void copyTo(Iterator <?扩展整数>它,列表<?超整型> out)'? – Cinnam
@Cinnam是的,你是对的。这是一个更好的解决方案。 –