このコードがあります:
public static class B1 {}
public static class B2 extends B1 {}
public void fun() {
List<? extends B1> l3 = new ArrayList<>();
l3.add(new B2());
}
コンパイル エラー:
java: no suitable method found for add(Main.B2)
method java.util.List.add(int,capture#1 of ? extends Main.B1) is not applicable
(actual and formal argument lists differ in length)
method java.util.List.add(capture#1 of ? extends Main.B1) is not applicable
(actual argument Main.B2 cannot be converted to capture#1 of ? extends Main.B1 by method invocation conversion)
これは、 B1 から拡張される任意の型? extends B1
を意味すると思います。タイプ B2 は B1 から拡張されているようですが、なぜこのタイプのオブジェクトをリストに追加できないのですか? また、追加できるようにする方法を教えてください。