我有以下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是的,你是對的。這是一個更好的解決方案。 –