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.
Arrays in Java are objects, and variables hold only references. Thus array1 = array2
only assigns array2
's reference to the variable array1
, and does not copy the contents.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With