Nested Generics with Wildcards

后端 未结 5 976
小鲜肉
小鲜肉 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:04

    Use,

    List<?> list1 = new LinkedList<List<Integer>>();
    
    0 讨论(0)
  • 2020-12-18 10:06

    Try

    List<? extends List<?>> list = new LinkedList<List<Integer>>();
    

    Note: you should be aware that when you use a collection like List you will only be able to use it in "read only" mode (except for adding null values).

    0 讨论(0)
  • 2020-12-18 10:11

    The way around this is

    List<List<?>> list = new LinkedList<List<?>>();
    

    You've not really lost anything there, either - your specification of Integer wasn't going to be helpful anywhere, since list defined the inner Lists as using ?

    0 讨论(0)
  • 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<?>> list = new LinkedList<List<?>>();
    list.add(new LinkedList<Integer>());
    list.add(new LinkedList<Double>());
    

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

    List<Object> listO = new List<Number>();
    

    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.

    0 讨论(0)
  • 2020-12-18 10:29

    I know this is and post, but I don't seem how the answers fixed c0d3x's problem.

    If you do

    List<List<?>> list = new LinkedList<List<?>>();
    

    How is he gonna call this method for each inner Integer list in the outer list?

    public void doSomeThingWithAIntegerList(List<Integer> list){
        for(Integer i : list){
            // use it for some purpose
        }
    }
    
    0 讨论(0)
提交回复
热议问题