Defqon
Defqon

Reputation: 107

Java - modifying copied array also effecting orignal array

I am copying an array and modifying the second array. How come this also modifies the original array that I copied it from. The code creates an array of random double between a given range of dimension length (X). Then, the array is copied to Y. The j'th element in Y is incremented by 2.2 and Y is sent to the schwefel benchmark function that returns a double value. Before X, Before Y, and After X should all be the same value since X isnt changing. Instead, After Y and After X are both the new value. Here is my code that is causing this:

    double alpha = 2.2;
    X = createArray(rangeMin, rangeMax, dimension);
    double[] Y = new double[dimension];
    for (int i = 0; i < iterations; i++) {
        Y = X;
        for (int j = 0; j < dimension; j++) {
            System.out.println("Before Y: " + runFunc(Y);
            System.out.println("Before X: " + runFunc(X);
            Y[j] += alpha;
            System.out.println("After Y: " + runFunc(Y);
            System.out.println("After X: " + runFunc(X);
            Y[j] -= alpha;
            }
        }

My output is for example:

Before Y: 894.3066859121232

Before X: 894.3066859121232

After Y: 825.661569833059

After X: 825.661569833059

Upvotes: 0

Views: 44

Answers (1)

0xh3xa
0xh3xa

Reputation: 4859

You didn't copy the array you have two references pointing to the same array the reference X and Y.

If you want to make a copy and not reflect in the original you can use clone() method

        double alpha = 2.2;
        X = createArray(rangeMin, rangeMax, dimension);
        double[] Y = X.clone();
        for (int i = 0; i < iterations; i++) {
            for (int j = 0; j < dimension; j++) {
                // logic
            }
        }

Upvotes: 2

Related Questions