Ren S
Ren S

Reputation: 59

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?

Upvotes: 3

Views: 5719

Answers (4)

user3133925
user3133925

Reputation:

When we do Changed = Original, we actually assigning reference of array. Hence if we make any change to one array, it would be reflected in other array as well because both Changed and Original refer to same location.

We can also use System.arraycopy() Method. System is present in java.lang package. Its signature is as :

public static void arraycopy(Object src, int srcPos, Object dest, 
                             int destPos, int length)

Upvotes: 0

Atef Hares
Atef Hares

Reputation: 4891

Everything in Java are passed-by value.. In case of Array(Which is nothing but an Object), array reference is passed by value.. (Just like an object reference is passed by value)..

When you pass an array to other method, actually the reference to that array is copied..

Any changes in the content of array through that reference will affect the original array.. But changing the reference to point to a new array will not change the existing reference in original method..

Use

System.arraycopy()

Check this

Upvotes: 4

jTerra
jTerra

Reputation: 1

When u copy an array like this:

changed = original;

you are copying the reference of the array. if you want to copy all the values from one array to other, you can do this:

for(int i = 0; i < original.size(); i++){
    changed[i] = original[i];
}

That`s one way you can do this. Doing this, if you change anything from the first one or the second one, the other will remain untouchable.

Hope i can help.

Upvotes: 0

Michael Asper
Michael Asper

Reputation: 96

 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()

Upvotes: 8

Related Questions