user6389648 user6389648 - 4 months ago 13
Java Question

Correct And Efficient Way to create 10 List in java?

How to make 10 Lists in java such as each list has variable amount of data.

MySolution:

I used the follwoing approach to solve this issue.

ArrayList a1=new ArrayList();
ArrayList a2=new ArrayList();
for(int i=0;i<5;i++)
{
for(int j=0;j<10;j++)
{
a1.add(0);
}
a2.add(a1);
}


But, this approach created only 1 list:
having the following elements when the user enters.

Output:

[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

Answer

You can do it as follows:

List<List<Integer>> outer=new ArrayList<>();

  for(int i=0;i<5;i++)
  {
     List<Integer> inner=new ArrayList<Integer>();
     for(int j=0;j<10;j++)
     {
       inner.add(0);
     }
     outer.add(inner);
  }

For more examples please go through the documentation of Java Collections