Java array changing itself

Asked

Viewed 42 times

0

Trying to create a method to randomly swap 2 lines of a matrix [n][2], whenever I try to create this new matrix, it changes the previous one too, no matter what I do, that is, after I run these lines of code, the value of individuals[0]. Individual, somehow changes and is equal to Newson.

            int[][] newSon = new int[coordenadasX.length/2][2];
            newSon = individuo[0].ordemIndividuos; 
            int random1 = r1.nextInt(coordenadasX.length);
            int random2 = r1.nextInt(coordenadasX.length);

            int temp1 = newSon[random1][0];
            int temp2 = newSon[random1][1];

            newSon[random1][0] = newSon[random2][0];
            newSon[random1][1] = newSon[random2][1];

            newSon[random2][0] = temp1;
            newSon[random2][1] = temp2;
  • 1

    What is individuo[0]? What is r1? If in the second line you are assigning something to newSon, then what you assigned in the first line will be forgotten.

  • Ah, what if newSon = individuo[0].ordemIndividuos, then any change in newSon will be a change in individuo[0].ordemIndividuos, for newSon is the variable you are using to reference the individuo[0].ordemIndividuos. Maybe what you wanted was to get newSon were a copy of individuo[0].ordemIndividuos, and not the very individuo[0].ordemIndividuos.

  • is exactly that, individual[0] is a vector of the individual class, and R1 is an object of the Random class, as I copy individual[0] to Newson?

1 answer

1

Instead:

int[][] newSon = new int[coordenadasX.length/2][2];
newSon = individuo[0].ordemIndividuos;

Do it:

int[][] original = individuo[0].ordemIndividuos;
int[][] newSon = new int[original.length][];
for (int i = 0; i < original.length; i++) {
    newSon[i] = original[i].clone();
}

Based in this reply by Soen.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.