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, but 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:
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 elements themselves are not copied.
If you want to make a deep copy of an array, where the elements themselves are also copied, you can use a loop to manually copy each element of the array to a new array.
I hope this helps! Let me know if you have any questions.