我对下面的代码有疑问。
你能告诉我为什么编译器拒绝接受 ty.add(new A()); 吗?毕竟 A 是 B 的父类(super class)(即符合要求)。
错误信息如下:
C.java:15: error: no suitable method found for add(A)
ty.add(new A());
^
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 A cannot be converted to CAP#1 by method invocation conversion)
where CAP#1 is a fresh type-variable:
CAP#1 extends Object super: B from capture of ? super B
1 error
这是代码(C.java):
import java.util.ArrayList;
import java.util.List;
class A
{
}
class B extends A
{
}
class C extends B
{
public static void main(String args[])
{
List<? super B> ty = new ArrayList<A>();
ty.add(new A());
ty.add(new B());
ty.add(new C());
}
}
最佳答案
你误解了什么? super B
方法。这意味着它是一个类,在编译时未知,即 B
或 B
的父类(super class)。编译器只知道 B
可以添加对象,毕竟它可能是 ArrayList<B>
。因此它必须禁止添加 A
.
允许添加 A
,考虑List<? super A>
或List<A>
对于 ty
的类型.
关于java - super 通配符导致的编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19303703/