How to copy an array
Short answer
clone() or Arrays.copyOf() create a new array with the same elements:
void main() {
int[] original = {1, 2, 3};
int[] copy = original.clone();
copy[0] = 99;
IO.println(Arrays.toString(original));
IO.println(Arrays.toString(copy));
}Output:
[1, 2, 3]
[99, 2, 3]A different length
Arrays.copyOf() lets you change the length at the same time — new elements are filled with zeros:
void main() {
int[] numbers = {1, 2, 3};
IO.println(Arrays.toString(Arrays.copyOf(numbers, 5)));
IO.println(Arrays.toString(Arrays.copyOf(numbers, 2)));
}Output:
[1, 2, 3, 0, 0]
[1, 2]Part of an array
Arrays.copyOfRange() copies elements from index from up to to (exclusive):
void main() {
String[] days = {"Mon", "Tue", "Wed", "Thu", "Fri"};
IO.println(Arrays.toString(Arrays.copyOfRange(days, 1, 4)));
}Output:
[Tue, Wed, Thu]Into an existing array
System.arraycopy() copies part of one array into another:
void main() {
int[] source = {1, 2, 3};
int[] target = new int[5];
System.arraycopy(source, 0, target, 2, 3);
IO.println(Arrays.toString(target));
}Output:
[0, 0, 1, 2, 3]Common mistake
Assigning an array to another variable and treating it as a copy. Both variables point to the same array:
void main() {
int[] original = {1, 2, 3};
int[] notACopy = original;
notACopy[0] = 99;
IO.println(Arrays.toString(original));
}Output:
[99, 2, 3]Also note: clone() copies only the array itself. If it holds mutable objects, the copy refers to the same objects.
Functions used in this recipe
- Arrays.copyOf() — Copies an array into a new one of the same or another length. copyOfRange() copies a part.