3

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));           

    }
3
  • Please post the full stack trace. Also, which type does storeIds have? Commented Sep 24, 2016 at 11:14
  • what's wrong with your current approach? Commented Sep 24, 2016 at 11:15
  • Sorry about that @Turing85. storeIds is of type List<String> Commented Sep 26, 2016 at 8:33

2 Answers 2

2

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));
Sign up to request clarification or add additional context in comments.

Comments

2

You need to create a new ArraraList and then add items to it

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

1 Comment

Some explanation would be beneficial.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.