Most efficient way to copy array in Java


The System class of java provides arraycopy method which is most efficient to copy one array data to another array.

public static void arraycopy(Object src, int srcPos,
       Object dest, int destPos, int length)

Using this you can copy one array data to another array using source position, destination position and length parameters of this method.

The components at positions srcPos through srcPos+length-1 in the source array are copied into positions destPos through destPos+length-1, respectively, of the destination array.

If the src and dest arguments refer to the same array object, then the copying is performed as if the components at positions srcPos through srcPos+length-1 were first copied to a temporary array with length components and then the contents of the temporary array were copied into positions destPos through destPos+length-1 of the destination array.

Example of arraycopy

public class ArrayCopyExample {

    public static void main(String[] args) {
        int[] copyFrom = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
        int[] copyTo = new int[7];

        System.arraycopy(copyFrom, 2, copyTo, 0, 7);
        for (int i : copyTo) {
            System.out.println(i);
        }
    }
}