0

is it possible to make dynamic ArrayList, for an example I have

List<String> Group = new ArrayList<String>();

I want to have dynamic arraylist like Group1, Group2, Group3 and so on... How do achieve this inside iteration?

for (int i = 0; i < n; i++) {
     List<String> Group+i = new ArrayList<String>(); // generate group-n
}

any suggestion?

3
  • may be ArrayList inside ArrayList? Commented Apr 1, 2016 at 8:06
  • No you cant create list of list in java. Better you use map instead or you can arrange data such that will not have list of list. Commented Apr 1, 2016 at 8:06
  • Possible duplicate of How do I dynamically name objects in Java? Commented Apr 1, 2016 at 8:28

3 Answers 3

0

Instead of list use arraylist and you can proceed ahead.

ArrayList<ArrayList<Integer>> outer = new ArrayList<ArrayList<Integer>>();
    ArrayList<Integer> inner = new ArrayList<Integer>();        
Sign up to request clarification or add additional context in comments.

Comments

0

Do you mean something like this?

List<List<String>> collectionOfLists = new ArrayList<List<String>>();
for(int i = 0; i < yourVar; i++){
    collectionOfLists.add(new ArrayList<String>());
}

You can then have any number of array lists and use them as you will

4 Comments

@SilvansSolanki Yep, works fine after I changed some little bits to not use the abstract classes
yes thats the reason I asked you, because your earlier code will give you exception and it will not worked. good that you make it correct.
see my updated post, is your code can generate arraylist like my post? if it can, how I call/use group2 for an example...
0

You can do like this..

for (int i = 1; i < n; i++)
    {    List<String> mylist$i   = new ArrayList<String>();}

it will give you

List<String> mylist1   = new ArrayList<String>();
List<String> mylist2   = new ArrayList<String>();
List<String> mylist3   = new ArrayList<String>();
List<String> mylist4   = new ArrayList<String>();

"$" can be used to join and create a new string/variable.

Comments

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.