Java: Instance double arrays element values modification issue

Viewed 98

I am new to Java. I have a class for which instances can be created. Within the class I define two instance variables:

double[] array1;

double[] array2;

The arrays will be of equal length.

Within the class I then have a method1 that first populates array1 and then another method2 in which I want to set some of the array2 values = the values in array1 (based on array element index) but also then modify (perform additional operation on) some of the values in array2 (based on array element index). I have tried to do this within method2 by first setting:

array2 = array1;

and then modifying some of the array2 values based on element index but I see that array1 has been completely modified to equal array2 so realise there is something fundamentally wrong with my approach in Java.

5 Answers

Arrays in Java are objects, and variables hold only references.
Thus array1 = array2 only assignes array2's reference to the variable array1, and does not copy the contents...

Assigning array2 = array1 sets array2 to point to the array as array1. Whenever you modify the array (e.g., array[0] = 123) both variables will "see" the change, since they both point to the same array. If you want to copy the elements of the array, you'll have to do so by iterating over the array and assigning values to it (or use a helper method that does just that, such as Arrays.copyOf). E.g.:

// Assumption: Both arrays are initialized and array1.length = array2.length

for (int i = 0; i < array1.length; ++i) {
    array2[i] = array1[i];
    // some additional logic on array2[i]
}

Instead of using assignment with array1 to set array2, you should probably use Arrays.copyOf():

array2 = Arrays.copyOf(array1, array1.length);

Hopefully that'll help

By doing array2=array1, you are adding a reference of array2 to array1. So whenever you make changes to array2, by virtue of reference, array1 will also change. You need to therefore copy values from one array to other and not pass reference from one array to other.

If you want an one-liner answer

System.arrayCopy(arrayA, 0, arrayB, 0, arrayB.length);

array2 = array1; points array2 reference to the same instance which is being referred by array1 which means that if you change a value using any one of these references, the value accessed using the other one will be same.

Do it as

array2 = array1.clone();

It will assign a copy of the instance referred by array1 to array2.

Demo:

public class Main {
    public static void main(String[] args) {
        int[] x = { 1, 2, 3 };
        int[] y = x.clone();
        x[2] = 5;
        System.out.println(x[2]);
        System.out.println(y[2]);
    }
}

Output:

5
3
Related