将数据添加到通用?扩展列表

scd*_*dmb 4 java generics

可能重复:
Java ArrayList?扩展接口

有这个代码:

public static class B1 {}
public static class B2 extends B1 {}
public void fun() {
    List<? extends B1> l3 = new ArrayList<>();
    l3.add(new B2());
}
Run Code Online (Sandbox Code Playgroud)

编译错误:

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)
Run Code Online (Sandbox Code Playgroud)

我猜这? extends B1意味着任何从B1延伸的类型.似乎B2类型从B1扩展,那么为什么这种类型的对象不能添加到列表中以及如何使它可以添加呢?

Oli*_*rth 8

我猜这? extends B1意味着任何从B1延伸的类型.

不是.它意味着"从B1延伸出来的特定但未知的类型".由于特定类型未知,编译器无法强制执行,因此操作add不起作用.*

请参阅有关通配符教程.

如何使它可以添加?

基本上,不要使用通配符.你可能想要这个:

List<B1> l3 = new ArrayList<B1>();
Run Code Online (Sandbox Code Playgroud)


*嗯,他们确实有效,但仅限于null(以及其他一些案例,请参阅下面的@Marko评论).