What are the different ways to copy an array in Java, and which one actually gives you an independent copy?
There are three ways to copy an array in Java, and only one of them gives you a copy that is completely independent of the original.
The first way is the one that catches people out. A plain assignment copies the reference, and not the data.
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] original = {1, 2, 3, 4};
// This copies the reference, not the data.
int[] same = original;
same[0] = 99;
System.out.println("original : " + Arrays.toString(original));
System.out.println("same : " + Arrays.toString(same));
System.out.println("same object : " + (original == same));
// This copies the data, so the two arrays are separate.
int[] copy = Arrays.copyOf(original, original.length);
copy[0] = 7;
System.out.println("after changing the copy : " + Arrays.toString(original));
System.out.println("copy is a different object : " + (original != copy));
}
}
The output shows that changing same changed original as well, because both names point at one array. The comparison original == same is true for the same reason.
The second way is the method Arrays.copyOf. It builds a new array with the values of the original, and the two arrays are then completely separate. You can also give it a different length, which is how you make a longer or a shorter copy.
The third way is the method clone, which is the same idea written with a different name. It is the one method on an array that the language treats specially.
So the answer to the question is that a plain assignment gives you a second reference to the same array, and Arrays.copyOf or clone gives you a real copy with its own storage.
The next question in this topic compares the two copying methods that do the job properly.