Java Generics: List, List<Object>, List<?>

后端 未结 12 2002
你的背包
你的背包 2020-11-22 17:08

Can someone explained, as detailed as possible, the differences between the following types?

List
List
List


Let me m

12条回答
  •  北恋
    北恋 (楼主)
    2020-11-22 17:44

    List, List, and List are the same thing. The second is more explicit. For a list of this type, you cannot know what types are legal to put into it, and you don't know anything about the types you can get out of it, except that they will be objects.

    List specifically means that the list contains any sort of object.

    Let's say we make a list of Foo:

    List foos= new ArrayList();
    

    It is not legal to put a Bar into foos.

    foos.add(new Bar()); // NOT OK!
    

    It is always legal to put anything into a List.

    List objs = new ArrayList();
    objs.add(new Foo());
    objs.add(new Bar());
    
    
    

    But you mustn't be allowed to put a Bar into a List - that's the whole point. So that means that this:

    List objs = foos; // NOT OK!
    
    
    

    is not legal.

    But it's ok to say that foos is a list of something but we don't know specifically what it is:

    List dontKnows = foos;
    

    But that then means that it must be prohibited to go

    dontKnows.add(new Foo()); // NOT OK
    dontKnows.add(new Bar()); // NOT OK
    

    because the variable dontKnows does't know what types are legal.

    提交回复
    热议问题