Search code examples
javaarraylistnested-loops

Tracing a Nested java for loop


The code segment is:

ArrayList<ArrayList<Integer>> outer = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> inner = new ArrayList<Integer>();
int count = 0;
for (int i = 0; i < 2; i++) {
    for (int j = 0; j < 3; j++) {
        count++;
        inner.add(count);
    }
    outer.add(inner);
}
System.out.println(outer);

I trace the loop like this: when i = 0, inner will be updated to [1, 2, 3]. Hence the outer will be [[1, 2, 3]].

When i = 1, inner will be updated to [1, 2, 3, 4, 5, 6]. Hence the output which is outer will be [[1, 2, 3], [1, 2, 3, 4, 5, 6]]

However, when I run the program, the output is actually [[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6]].

Why is this so?

Thanks

I have edited the code


Solution

  • Here is Complete Working code what you try to print Exactly. Try this out.

         ArrayList<ArrayList<Integer>> outer = new ArrayList<ArrayList<Integer>>();
         ArrayList<Integer> inner ;
            for (int i = 1; i <= 2; i++) {
                inner = new ArrayList<Integer>(); //each time new ArrayList<Integer> Need to Create. 
               for (int j = 1; j <= i*3; j++) {
    
                   inner.add(j);
            }
              outer.add(inner);
          }
    System.out.println(outer);
    

    Output :

    [[1, 2, 3], [1, 2, 3, 4, 5, 6]]
    

    Mistake that you do is You are not creating different object of ArrayList<Integer> at each Iteration of Outer loop i. So, each and every time if you add the int count will be added to the same object.

    eg:- In First Iteration when i = 1 then inner loop will add [1,2,3] to the inner ArrayList.

    In Second Iteration when i=2 then inner loop again Initialize the previous inner ArrayList Object which already contains [1,2,3] Now you add [4,5,6] to it. So ArrayList<Integer> inner become [ 1 , 2 , 3 , 4 , 5 , 6 ].

    Hope got your mistake.