Android array new value replaces old values

A common gotcha in Android development!

In Android, when you create a new array and assign it to a variable, it does not create a copy of the original array. Instead, it creates a new reference to the same array. This means that if you modify the new array, you will also be modifying the original array.

Here's an example:

int[] myArray = {1, 2, 3};
int[] newArray = myArray; // creates a new reference to the same array

newArray[0] = 10; // modifies the original array

Log.d("Array", Arrays.toString(myArray)); // prints [10, 2, 3]

As you can see, modifying the newArray also modified the original myArray.

To avoid this behavior, you can create a copy of the array using one of the following methods:

  1. Using Arrays.copyOf():
    
    int[] myArray = {1, 2, 3};
    int[] newArray = Arrays.copyOf(myArray, myArray.length);

newArray[0] = 10; // modifies the new array, not the original

Log.d("Array", Arrays.toString(myArray)); // prints [1, 2, 3]

2. Using a loop to copy the elements:
```java
int[] myArray = {1, 2, 3};
int[] newArray = new int[myArray.length];
for (int i = 0; i < myArray.length; i++) {
    newArray[i] = myArray[i];
}

newArray[0] = 10; // modifies the new array, not the original

Log.d("Array", Arrays.toString(myArray)); // prints [1, 2, 3]
  1. Using a library like Apache Commons Lang, which provides a ArrayUtils class with a copy() method:
    
    import org.apache.commons.lang3.ArrayUtils;

int[] myArray = {1, 2, 3}; int[] newArray = ArrayUtils.copy(myArray);

newArray[0] = 10; // modifies the new array, not the original

Log.d("Array", Arrays.toString(myArray)); // prints [1, 2, 3]


By creating a copy of the array, you can modify the new array without affecting the original array.