Arraylist of int[] array

Sha

New Member
#1
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:
Mã:
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:
Mã:
[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]
 

Admin

Administrator
Thành viên BQT
#2
You are adding the same int[] instance to the list repeatedly.
Mã:
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)));
}
Nothing in this list ever calls list = new int[7]. That means that each time through, you overwrite the contents of list with new random numbers, then add the same list to the ArrayList again.

ArrayList will happily let you add the same object over and over. It's just important to understand that putting an object into the ArrayList doesn't somehow copy it or anything.
 
Top