I am trying a simple code and I can't figure out what is wrong. I am trying to add int[] array to an ArrayList. It gets added correctly. But once I have more than 1 element in the ArrayList, each of the element in the list is replaced by the latest value. I tried looking for possible errors, but I couldn't find any. I am giving my code and output here so that I can get help in figuring out the error in the code.
Code:
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Arrays;
public class main {
public static void main(String[] args) {
ArrayList<int[]> outer = new ArrayList<int[]>();
int[] list = new int[7];
int total = 2;
int l = 3;
SecureRandom rand = new SecureRandom();
for (int i = 0; i < total; i++)
{
if((i+1) % l == 0)
{
list = new int[7];
outer = new ArrayList<int[]>();
}
else {
for(int j = 0; j < 7; j++)
{
int num = rand.nextInt(100);
list[j] = num;
}
System.out.println(Arrays.toString(list));
outer.add(list);
System.out.println(outer.size());
System.out.println(i);
System.out.println(Arrays.toString(outer.get(i)));
}
}
System.out.println(Arrays.toString(outer.get(0)));
System.out.println(Arrays.toString(outer.get(1)));
}
}
The output I get is:
Output:
[13, 50, 3, 47, 53, 57, 61]
1
0
[13, 50, 3, 47, 53, 57, 61]
[66, 96, 45, 2, 95, 1, 69]
2
1
[66, 96, 45, 2, 95, 1, 69]
[66, 96, 45, 2, 95, 1, 69]
[66, 96, 45, 2, 95, 1, 69]