How can elements be added to a wildcard generic collection?

后端 未结 5 1926
陌清茗
陌清茗 2020-11-28 12:25

Why do I get compiler errors with this Java code?

1  public List getFoos()
2  {
3    List foos = new ArrayList

        
5条回答
  •  北海茫月
    2020-11-28 12:32

    The following will work fine:

    public List getFoos() {
        List foos = new ArrayList();
        foos.add(new SubFoo());
        return foos;
    }
    

提交回复
热议问题