0
ArrayList<ArrayList<Integer>> aal=new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> al= new ArrayList<Integer>();
for(int i=2;i<6;i++)
{
    al.add(i);
    if(i%2!=0)
    {
        aal.add(al);
        al.clear();
    }
}

Output: [[4,5][4,5]]

Required output: [[2,3][4,5]]

Dino
  • 7,779
  • 12
  • 46
  • 85

1 Answers1

2

al.clear() will also clear the contents of the array list that you have just put into aal. This is because the array list in aal and the one referenced by al are the same array list. Here are two ways you can fix this.

  1. Create a new array list after adding to aal:

    for(int i=2;i<6;i++)
    {
        al.add(i);
        if(i%2!=0)
        {
            aal.add(al);
            al = new ArrayList<>();
        }
    }
    
  2. Add a copy of al to aal (this is probably what you expected your code would do):

    for(int i=2;i<6;i++)
    {
        al.add(i);
        if(i%2!=0)
        {
            aal.add(new ArrayList<>(al));
            al.clear();
        }
    }
    

Notice in both of these cases, I am creating new array lists with new ArrayList<>.

Sweeper
  • 213,210
  • 22
  • 193
  • 313