Make copy of an array
To make a copy of an array in Java, you can use the clone() method of the Object class. The clone() method creates a shallow copy of the array, which means that it creates a new array with the same elements as the original array
To make a copy of an array in Java, you can use the clone() method of the Object class. The clone() method creates a shallow copy of the array. For primitive arrays, this results in a completely independent copy of the values. For arrays of objects, it creates a new array containing references to the same objects, meaning the elements themselves are not copied.
Here's an example of how you can use the clone() method to make a copy of an array:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] arr = {1, 2, 3};
int[] copy = arr.clone();
// Modify the original array
arr[0] = 10;
// Print the original and copy arrays
System.out.println(Arrays.toString(arr)); // [10, 2, 3]
System.out.println(Arrays.toString(copy)); // [1, 2, 3]
}
}In this example, the arr array is cloned to create the copy array. Modifying the original array does not affect the copy, since the primitive values are copied directly.
If you need a deep copy of an array containing objects, where each element is independently duplicated, you must manually copy them. Here is an example using a loop:
String[] original = {"A", "B", "C"};
String[] deepCopy = new String[original.length];
for (int i = 0; i < original.length; i++) {
deepCopy[i] = new String(original[i]); // Creates independent copies of each element
}