Copying arrays

suggest change

Java provides several ways to copy an array.

for loop

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.

Object.clone()

Since arrays are Objects 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.


Arrays.copyOf()

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);

System.arraycopy()

`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]

Arrays.copyOfRange()

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]

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Arrays:
* Arrays
* Copying arrays

Table Of Contents
8 Arrays
10 Maps
11 Strings
25 JAXB
29 Enums
32 Audio
41 Scanner
63 Logging
75 Lists
78 Sets
89 JAX-WS
96 XJC
98 Process
106 Modules
114 Applets
122 JNDI
139 JavaBean
141 Literals
144 Packages
150 JMX
153 JShell
159 Sockets
167 Enum Map
175 Hashtable
177 SortedMap