kai kai - 4 months ago 20
Java Question

How to initialize inner ArrayList of a two-dimensional ArrayList

The below ArrayList is a two-dimensional ArrayList of size parts. I'm divding the storeIds into parts of ArrayList and add them to the inner ArrayList of the 2D ArrayList.

ArrayList<ArrayList<String>> partStoreIds = new ArrayList<ArrayList<String>>(parts);
for(int i = 0; i < parts; i++)
System.out.println("Executing part: " + i);
int maxIndex = Math.min(storeIds.size(), querySize*(i+1));
//The below line is throwing an exception
partStoreIds.addAll(storeIds.subList(querySize*i, maxIndex));



What you try to achieve can be done as next:

partStoreIds.add(new ArrayList<>(storeIds.subList(querySize*i, maxIndex)));

Indeed, as partStoreIds is an ArrayList of ArrayList only ArrayList instances can be added and since storeIds.subList(querySize*i, maxIndex) returns a List, you need to convert it first as an ArrayList using the constructor new ArrayList(Collection).

But a much simpler approach would be to declare your partStoreIds as a List of List, then you can add your subList directly as next:

List<List<String>> partStoreIds = new ArrayList<>(parts);
    partStoreIds.add(storeIds.subList(querySize*i, maxIndex));