我一直在用 Java 测试超类型泛型,但遇到了障碍。这是我正在测试的示例代码:
import java.util.*;
class GenericTests {
public static void main( String[] args ) {
List<B> list3 = new ArrayList<B>();
testMethod( list3 );
}
public static void testMethod( List<? super B> list ) {
list.add( new A() );
list.add( new B() );
}
}
class A { }
class B extends A { }
编译时,错误是:
GenericTests.java:20: error: no suitable method found for add(A)
list.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 conve
rsion)
where CAP#1 is a fresh type-variable:
CAP#1 extends Object super: B from capture of ? super B
1 error
我认为给定 B 的下限,您可以添加任何超类型?或者这是否仅适用于引用(即方法签名中的参数),因为允许超类型会破坏类型检查?