What are the different ways to copy an array in Java, and which one actually gives you an independent copy?
There are four ways to do it, and only three of them copy anything. Assigning one array variable to another — int[] b = a; — copies the reference, not the data. Both names then point at the same array, so a write through one is visible through the other. It is the single most common array bug in Java, and it is why == on two array variables is usually a mistake in the first place.
The three genuine copies are Arrays.copyOf, the clone method on the array type, and System.arraycopy. All three allocate a new array and copy the elements into it, so the result is independent of the original for primitives.
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] original = {1, 2, 3, 4};
// 1. The assignment: both names point at the same array.
int[] same = original;
same[0] = 99;
System.out.println("after same[0]=99, original[0] = " + original[0]);
// 2. A real copy.
int[] copy = Arrays.copyOf(original, original.length);
copy[0] = 7;
System.out.println("after copy[0]=7, original[0] = " + original[0]);
// 3. A partial copy.
int[] partial = Arrays.copyOf(original, 2);
System.out.println("partial copy : " + Arrays.toString(partial));
// 4. clone() does the same job.
int[] cloned = original.clone();
cloned[1] = 50;
System.out.println("after cloned[1]=50, original[1] = " + original[1]);
}
}The output is the clearest demonstration of the difference. After same[0] = 99 the original shows 99, because there is only one array. After copy[0] = 7 the original still shows 99, because the copy is a separate array. The partial copy holds the first two elements of the original as it stood at that moment, and the cloned array behaves exactly like the copy.
Two footnotes. clone on an array returns the array type, not Object, because the language special-cases it; and it performs a shallow copy, which matters as soon as the elements are objects rather than primitives.