Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing value in one array changes value in another array

I have really strange problem. In activity I declare two arrays

private String original[] = new String[100];
private String changed[] = new String[100];

Then I assign values to those two arrays in OnCreate:

Bundle extras = getIntent().getExtras();

if (extras != null) {
      original = extras.getStringArray("sentArray");

      changed = original;
}

Now if I change values of members of changed array, original array will also have that members changed.

For example, after I do

changed[0] = "New value";

value of original[0] is also "New value".

How is something like that possible? Is this a bug?

like image 360
Ren S Avatar asked May 07 '26 20:05

Ren S


1 Answers

 changed = original;

This line is setting 'changed' to 'original' so they're the same array with the same pointers. You need to copy the array instead of setting changed equal to original.

You can try using System.arraycopy()

like image 81
Michael Asper Avatar answered May 10 '26 09:05

Michael Asper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!