How can elements be added to a wildcard generic collection?

后端 未结 5 1932
陌清茗
陌清茗 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条回答
  •  猫巷女王i
    2020-11-28 12:56

    Use this instead:

    1  public List getFoos()
    2  {
    3    List foos = new ArrayList(); /* Or List */
    4    foos.add(new SubFoo());
    5    return foos;
    6  }
    

    Once you declare foos as List, the compiler doesn't know that it's safe to add a SubFoo. What if an ArrayList had been assigned to foos? That would be a valid assignment, but adding a SubFoo would pollute the collection.

提交回复
热议问题