Java Copy Array

In Java, there are several ways to copy the elements of an array to another array. The simplest way is to use a loop to copy each element one by one, like this:

refer to:‮editfigi‬a.com
int[] sourceArray = {1, 2, 3, 4, 5};
int[] destinationArray = new int[sourceArray.length];
for (int i = 0; i < sourceArray.length; i++) {
    destinationArray[i] = sourceArray[i];
}

This creates a new array called destinationArray with the same length as sourceArray, and then copies the elements of sourceArray to destinationArray one by one.

Java also provides a built-in method called arraycopy() in the System class that can be used to copy elements between arrays. Here's an example of how to use this method:

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

This code creates a new array called destinationArray with the same length as sourceArray, and then copies the elements of sourceArray to destinationArray using the arraycopy() method.

Another way to copy an array is to use the clone() method, which creates a new array that is a copy of the original array. Here's an example:

int[] sourceArray = {1, 2, 3, 4, 5};
int[] destinationArray = sourceArray.clone();

This code creates a new array called destinationArray that is a copy of sourceArray.

It's important to note that all of these methods create a new array that is a copy of the original array. If you modify one array, it will not affect the other array.