Inserting various arrays into an ArrayList

I inserted the array into ArrayList, but after inserting the second, the first became the same as the second.

Main class:

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");
    }

      

The Rand function // is a random function that generates random values ​​in 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 have run it many times, but the values ​​of both arrays are the same.

results

I couldn't figure it out why not get the same values ​​of both arrays.

+3


source to share


4 answers


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 create an array, set its value, and add it to the list. Then you change the values ​​of the same array and add it again again. Therefore, the list contains the same array twice . The array itself contains the random numbers of the second iteration.

+6


source


You add the array parent

to the ArrayList, then change the values parent

, and then add it again to the ArrayList. ArrayList holds int [] by reference, so when you change values ​​in parent

, you change values ​​in list.get (0)



You need to create a new array every time you add to ArrayList

+2


source


Plain:

int[] parent = new int[4];

      

required in your cycle.

Otherwise, you will add an instance of the same array several times to this list.

+2


source


Since you are adding the same array object parent

to your 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); // it still the same object, but now twice in the arraylist
}

      

To fix this, you can move it to a for loop like this

for (int i = 0; i < 2; i++) {
 int[] parent = new int[4];
 .....
}

      

The reason you see duplicate array values ​​is because it is not duplicated, but more like the same array that is available twice in your ArrayList

.

+1


source







All Articles