0

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

1 Answer 1

2

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
            }
        }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.