How can elements be added to a wildcard generic collection?

后端 未结 5 1931
陌清茗
陌清茗 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:37

    To get an idea of how generics works check out this example:

        List sfoo = new ArrayList();
        List foo;
        List tmp;
    
        tmp = sfoo;
        foo = (List) tmp;
    

    The thing is, that wasn't designed for local/member variables, but for function signatures, that's why it's so ass-backwards.

提交回复
热议问题