Nested Generics with Wildcards

后端 未结 5 999
小鲜肉
小鲜肉 2020-12-18 09:32

Why does this work:

List list = new LinkedList();

while this gives a type dismatch error:

List

        
5条回答
  •  遥遥无期
    2020-12-18 10:17

    To actually answer your question:

    In the first case, "list" holds a list of one particular, unspecified type - in this case, Integer.

    In the second case, "list" holds a list of lists, but each of the sublists may be of any particular type, but the following would be perfectly fine (note the types of the two lists being added):

    List> list = new LinkedList>();
    list.add(new LinkedList());
    list.add(new LinkedList());
    

    It's very similar to the reason why you can't do

    List listO = new List();
    
    
    

    There are operations that would be perfectly valid on your list of lists of ? that would be illegal on the list of lists of Integers.

    In order to do what you want (have a list of lists, where all the sublists are unique to a particular type), I think Zed's answer is about as close as you'll get.

    提交回复
    热议问题