Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 392
2one Avatar asked Dec 05 '22 08:12

2one


1 Answers

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.

like image 110
Usagi Miyamoto Avatar answered Dec 07 '22 23:12

Usagi Miyamoto