Java Copying Arrays Using arraycopy() method

Java Copying Arrays Using arraycopy() method

The System.arraycopy method is a convenient way to copy the elements of one array to another array in Java. It has the following syntax:

System.arraycopy(src, srcPos, dest, destPos, length);
S‮uo‬rce:www.lautturi.com

Here, src is the source array, srcPos is the starting position in the source array, dest is the destination array, destPos is the starting position in the destination array, and length is the number of elements to be copied.

For example, to copy the elements of an int array called original to another int array called copy, you can use the following code:

int[] original = {1, 2, 3, 4, 5};
int[] copy = new int[original.length];
System.arraycopy(original, 0, copy, 0, original.length);

This code creates a new int array called copy with the same length as the original array, and uses the System.arraycopy method to copy the elements of the original array to the copy array.

Note that the System.arraycopy method is a native method implemented in the Java Native Interface (JNI) layer, which makes it faster than other methods of copying arrays, such as using a loop. However, it is important to note that the System.arraycopy method can only be used to copy arrays of the same type. If you try to use it to copy arrays of different types, you will get a runtime error.

Created Time:2017-11-03 00:14:37  Author:lautturi