为什么我无法将派生对象添加到List <! - ?扩展Base - >?

时间:2015-12-03 07:19:42

标签: java generics

我写了这样的代码:

public class Generic {
    interface Base {}

    static class Derived implements Base {

    }

    public static void main(String args[]) {
        List<? extends Base> list = new ArrayList<>();
        list.add(new Derived());//line 16
    }
}

错误:

Error:(16, 13) java: no suitable method found for add(Generic.Derived)
    method java.util.Collection.add(capture#1 of ? extends Generic.Base) is not applicable
      (argument mismatch; Generic.Derived cannot be converted to capture#1 of ? extends Generic.Base)
    method java.util.List.add(capture#1 of ? extends Generic.Base) is not applicable
      (argument mismatch; Generic.Derived cannot be converted to capture#1 of ? extends Generic.Base)

0 个答案:

没有答案