Java provides several ways to copy an array.
int[] a = { 4, 1, 3, 2 };
int[] b = new int[a.length];
for (int i = 0; i < a.length; i++) {
b[i] = a[i];
}
Note that using this option with an Object array instead of primitive array will fill the copy with reference to the original content instead of copy of it.
Since arrays are Object
s in Java, you can use Object.clone()
.
int[] a = { 4, 1, 3, 2 };
int[] b = a.clone(); // [4, 1, 3, 2]
Note that the Object.clone
method for an array performs a shallow copy, i.e. it returns a reference to a new array which references the same elements as the source array.
java.util.Arrays
provides an easy way to perform the copy of an array to another. Here is the basic usage:
int[] a = {4, 1, 3, 2};
int[] b = Arrays.copyOf(a, a.length); // [4, 1, 3, 2]
Note that Arrays.copyOf
also provides an overload which allows you to change the type of the array:
Double[] doubles = { 1.0, 2.0, 3.0 };
Number[] numbers = Arrays.copyOf(doubles, doubles.length, Number[].class);
public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
Copies an array from the specified source array, beginning at the specified position, to the specified position of the destination array.
Below an example of use
int[] a = { 4, 1, 3, 2 };
int[] b = new int[a.length];
System.arraycopy(a, 0, b, 0, a.length); // [4, 1, 3, 2]
Mainly used to copy a part of an Array, you can also use it to copy whole array to another as below:
int[] a = { 4, 1, 3, 2 };
int[] b = Arrays.copyOfRange(a, 0, a.length); // [4, 1, 3, 2]