泛型:尝试将参数化集合传递给List addAll方法

VB_*_*VB_ 3 java generics collections

我有代码(完整的源代码):

public class AutoConversionTest {

    @Test
    public void test_autoConversion() {
        Wrapper wrapper = new Wrapper();
        wrapper.setList(new ArrayList<Sub>());
        wrapper.addAll(new ArrayList<Sub>());
    }

    class Wrapper {
        List<? extends Super> list;

        public void setList(List<? extends Super> list) {
            this.list = list;
        }

        public void addAll(List<? extends Super> list) {
            this.list.addAll(list);  //TROUBLES!
        }
    }

    class Super {}

    class Sub extends Super {}
}
Run Code Online (Sandbox Code Playgroud)

问题:Wy错误以及如何解决它?

编辑:我的错误日志

java: no suitable method found for `addAll(java.util.List<? extends expectations.public_method.experiments.AutoConversionTest.Super>)`
 method `java.util.List.addAll(int,java.util.Collection<? extends expectations.public_method.experiments.AutoConversionTest.Super>)` is not applicable (actual and formal argument lists differ in length)
 method `java.util.List.addAll(java.util.Collection<? extends expectations.public_method.experiments.AutoConversionTest.Super>)` is not applicable (actual argument `java.util.List<? extends expectations.public_method.experiments.AutoConversionTest.Super>` cannot be converted to `java.util.Collection<? extends expectations.public_method.experiments.AutoConversionTest.Super>` by method invocation conversion)
Run Code Online (Sandbox Code Playgroud)

JB *_*zet 7

List<? extends Super>意思是:一些未知类型的列表,它扩展了Super.因此,您不能向此类列表添加任何内容(null除外),因为您不知道其元素的类型.如果编译器允许这样做,则可以OtherSub向a 添加实例List<Sub>,这会破坏列表的类型安全性.

改变的类型Wrapper.listList<Super>.

编辑:

修改后的代码

class Wrapper {
    List<Super> list;

    public void setList(List<? extends Super> list) {
        this.list.clear();
        this.list.addAll(list);
    }

    public void addAll(List<? extends Super> list) {
        this.list.addAll(list);
    }
}
Run Code Online (Sandbox Code Playgroud)