Search code examples
javaarraysinstance-variables

Java: Instance double arrays element values modification issue


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.


Solution

  • 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