【发布时间】:2021-08-20 08:08:23
【问题描述】:
我有 2 个使用通用通配符链接的类
import java.util.*;
public class Main
{
public static void main(String[] args){
AnotherClass another = new AnotherClass();
List<Integer> a1 = new ArrayList<Integer>();
a1.add(1);
another.runtest(a1);
}
}
import java.util.*;
public class AnotherClass {
public void runtest(List<? extends Number> a){
a.add(2);
}
}
但在执行上述代码时,我遇到如下异常:
AnotherClass.java:4: error: no suitable method found for add(int)
a.add(2);
^
method Collection.add(CAP#1) is not applicable
(argument mismatch; int cannot be converted to CAP#1)
method List.add(CAP#1) is not applicable
(argument mismatch; int cannot be converted to CAP#1)
where CAP#1 is a fresh type-variable:
CAP#1 extends Number from capture of ? extends Number
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
1 error
有人可以帮助我以更好的方式编写代码,或者我们如何在方法调用期间使用通配符。我无法理解为什么它现在允许在方法定义中扩展。
【问题讨论】:
-
请从代码围栏中删除您的第一行。
-
@BenjaminM 非常感谢您的参考。它解决了我所有的疑惑。 :)
-
List<? extends Number>是一个列表,其中包含Number的 some 子类的 some ok 实例 - 很明显,你不知道是哪个。它可能是List<Integer>、List<Double>,甚至是List<MyCustomImplementationOfNumber>。因此,编译器不知道添加Integer是否安全。