Java – insert different arrays in ArrayList

I inserted an array in ArrayList, but after inserting the second array, the first array is the same as the second array

Main category:

public static void main(String[] args) {

    ArrayList<int[]> list = new ArrayList<>();

    int[] parent = new int[4];

    for (int i = 0; i < 2; i++) {
        parent[0] = rand(4,1);
        parent[1] = rand(6,-2);
        parent[2] = rand(2,1);
        parent[3] = rand(-1,-2);

        list.add(parent);
    }

    // to print the arrays of the parent
    for (int i = 0; i < 2; i++) {
        int[] arr ;
        arr = list.get(i);
        for (int j = 0; j < arr.length; j++) {
            System.out.println("Value "+arr[j]);
        }
        System.out.println("Next Array");
    }

Rand function / / it is a random function that generates random values within a range

public static int rand(int max,int min)
{
  Random rand = new Random();
  int value = 0;
  return value = rand.nextInt(max + 1 - min) + min; 
}

I've run it many times, but the values of both arrays are the same

Results

I can't understand why I get the same value of two arrays

Solution

Change your code to

for (int i = 0; i < 2; i++) {
    int[] parent = new int[4];
    parent[0] = rand(4,1);
    parent[1] = rand(6,-2);
    parent[2] = rand(2,1);
    parent[3] = rand(-1,-2);

    list.add(parent);
}

Otherwise, you are creating an array, setting its value, and adding it to the list You will then change the value of the same array and add it again So the list contains the same array twice The array itself contains the random number of the second iteration

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>