Skip to main content

How do I copy array elements

In this Q&A we'll go over APIs available to copy elements from source to destination array

System.arrayCopy method copies array elements from source and destination.  Destination array has to be created before calling this method.  See the code below:
int[] ia = {1,2,3,4};
int[] iac = {101,102,103,104};
System.arraycopy(ia, 0, iac, 0, ia.length);
assertEquals( "Equals check", true, Arrays.equals(ia, iac)); 

Arrays.copyOf methods creates a new array and copies elements. 
int[] ia = {1,2,3,4};
int[] iac2 = Arrays.copyOf(ia, ia.length);
assertEquals( "Equals check", true, Arrays.equals(ia, iac2));

Using Arrays.stream one can copy array elements.  See code below 
Integer[] io = {1,2,3,4};
Integer[] io2 = Arrays.stream(io).toArray(Integer[]::new);
assertEquals( "Equals check", true, Arrays.equals(io, io2));

The above three methods shallow copies array of objects. One can use Apache commons SerializationUtils.clone method to deep copy objects from source to destination
int[] ia = {1,2,3,4};
int[] iac3 = SerializationUtils.clone(ia);
assertEquals( "Equals check", true, Arrays.equals(ia, iac3));
assertEquals( "Equals check", false, ia.equals(iac3));

Comments