简体   繁体   中英

initializing a multidimensional list with n empty 1D lists in Java

I have a multi-dimensional List

List<List<Integer>> myList;

I want it its dimension to be specified at run time, so in the code, I put:

myList = Collections.synchronizedList(new ArrayList<List<Integer>>(n));

I was hoping this would initialize mylist as a list with n elements each having zero elements but that didn't happen. I only get an empty list. apparently that constructor, "Constructs an empty list with the specified initial capacity." which is not quite what I want.

I understand that I can loop over mylist and add() empty one-dimensional lists, but is there any way of achieving what I want with less codes of code?

First of all the constructor ArrayList<T>(int capacity) does not insert any element in the list, so you are not specifying a size but an initial capacity.

Basically you allow the list to insert up to n elements without the need of internal resizing.

So the outer list is still empty. You can't use Collections.fill because you need a different internal List<Integer> every time, and fill would just set all elements to the same reference. So you are forced to insert them manually:

for (int i = 0; i < n; ++i)
  myList.add(new ArrayList<Integer>());

Mind that in any case, since you specified it as a List<List<Integer>> (which makes sense), Java wouldn't be able to default initialize anything, since List<Integer> in just an interface.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM