How to fill a List of Lists?

后端 未结 3 1999
我在风中等你
我在风中等你 2021-01-26 20:47

I create a list of lists like this:

List tmp = new ArrayList(2);

Then I\'d like to insert 10 to first sub-list as follo

相关标签:
3条回答
  • 2021-01-26 21:03

    You haven't added anything to the list yet. Declaring a List of any type with an initial capacity of 2 doesn't automatically populate that. You have to do that first.

    0 讨论(0)
  • 2021-01-26 21:29

    You've created an empty list with initial capacity of 2 (i.e. the internal representation of the list won't be resized until you've added 2 elements to it and are adding the third).

    Then you try to get the first element from the empty list. Naturally this won't work. You need to first add() as many inner lists (presumably 2) as you want, and then fill those inner lists.

    0 讨论(0)
  • 2021-01-26 21:30

    You have not initialized the inner list. That's the reason you are getting the error.

    Following code will initialize each of the inner list.

    int initialCapacity=2;
    List<List> tmp = new ArrayList<List>(initialCapacity);
    for(int i = 0; i < initialCapacity; i++)
         tmp.add(new ArrayList());
    
    0 讨论(0)
提交回复
热议问题