0

I have the following code written down.

    ArrayList<int []> l = new ArrayList<>();
    int [] temp = new int[2];
    int n=1;
    for(int i=0;i<10;i++)
    {
        for(int j=0;j<2;j++)
        {
            temp[j]=n++;
        }
        l.add(temp);
    }

    for(int i=0;i<10;i++)
    {
        for(int j=0;j<2;j++)
        {
            System.out.print(l.get(i)[j] + " ");
        }
        System.out.println();
    }

The output:

 19 20 
 19 20 
 19 20 
 .
 .
 19 20

I cannot understand why the output is such. i am populating the list with temp array which is changing each time. What am i doing wrong?

Hassan Naqvi
  • 933
  • 5
  • 18

1 Answers1

7

You are populating the List with multiple references to the same array object. You must create a new array in each iteration of the loop that adds elements to the List.

for (int i = 0; i < 10; i++) {
    int [] temp = new int[2];
    for (int j = 0; j < temp.length; j++) {
        temp[j] = n++;
    }
    l.add(temp);
}
Eran
  • 387,369
  • 54
  • 702
  • 768