Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically creating ArrayList inside a loop

Tags:

java

arraylist

How do we create arraylist dynamically inside a loop?

something like -

for(i=0;i<4;i++)  
{  
List<Integer> arr(i) = new ArrayList<>();  
}         
like image 347
Preethi Avatar asked Nov 29 '22 08:11

Preethi


1 Answers

It sounds like what you actually want is a list of lists:

List<List<Integer>> lists = new ArrayList<List<Integer>>();
for (int i = 0; i < 4; i++) {
    List<Integer> list = new ArrayList<>();
    lists.add(list);
    // Use the list further...
}

// Now you can use lists.get(0) etc to get at each list

EDIT: Array example removed, as of course arrays of generic types are broken in Java :(

like image 177
Jon Skeet Avatar answered Dec 04 '22 16:12

Jon Skeet