You can actually take a look at the code if you want to understand what's happening. In your case, let's take a look at java.util.Arrays#asList(T...)
@SafeVarargs
public static <T> List<T> asList(T... var0) {
return new Arrays.ArrayList(var0); // notice this
}
It returns an inner class called 'ArrayList' (not to be confused with java.util.ArrayList
, these are different classes, but they do more or less the same thing).
// the inner class
private static class ArrayList<E> extends AbstractList<E> implements RandomAccess, Serializable {
private final E[] a;
ArrayList(E[] var1) {
this.a = Objects.requireNonNull(var1); // directly reuses the array you pass in
}
}
Based on this code, we see that the array is reused. It's also important to note that Java will pass arrays as is rather than as a copy in parameters. What does that mean?
int[] arr = { 1, 2, 3, 4, 5 };
modifyArray(arr);
assert arr[0] == 2; // true
void modifyArray(int[] array) {
array[0] = 2;
}
Due to this, we can confirm we will share the array instance across parameters. For that reason, when you mutate the array from your scope, you are indirectly affecting the backing array for Arrays$ArrayList
.