What is the function of system.arraycopy in Java?

The System.arraycopy() method in Java is used to copy arrays. It allows copying a portion of one array to a specific position in another array.

The syntax for the System.arraycopy() method is as follows:

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

Explanation of parameters:

  1. source array, refers to the array that needs to be copied.
  2. srcPos: The starting position of the source array, indicating from which position to begin copying.
  3. Destination: The array where the data will be copied to.
  4. destPos: The starting position in the target array where the data will be copied.
  5. number of elements to be copied.

The System.arraycopy() method copies a specified number of elements from a starting position in the source array to a specified position in the destination array.

Below is a simple example demonstrating how to use the System.arraycopy() method to copy an array:

public class ArrayCopyExample {
    public static void main(String[] args) {
        int[] sourceArray = {1, 2, 3, 4, 5};
        int[] destinationArray = new int[5];

        System.arraycopy(sourceArray, 0, destinationArray, 0, sourceArray.length);

        for (int i = 0; i < destinationArray.length; i++) {
            System.out.print(destinationArray[i] + " ");
        }
    }
}

The code above copies the source array sourceArray to the destination array destinationArray and outputs the content of the destination array. The output result is: 1 2 3 4 5.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds