Cloning an array is a straightforward way to create a shallow copy of it. The clone()
method allows you to duplicate an array so that modifications to the new array don’t affect the original one. However, it’s essential to understand that clone()
only creates a shallow copy of the array, which has implications when the array contains reference types.
clone()
MethodTo clone an array in Java, simply call the clone()
method on the array:
int[] originalArray = {1, 2, 3, 4, 5};
int[] clonedArray = originalArray.clone();
After calling clone()
, clonedArray
will be a new array that has the same elements as originalArray
. Changes to clonedArray
won’t affect originalArray
and vice versa.
The clone()
method performs a shallow copy. This means:
int
, float
, etc.), each element in the cloned array is a copy of the original.Example of shallow copy behavior with an array of objects:
String[] originalArray = {"apple", "banana", "cherry"};
String[] clonedArray = originalArray.clone();
clonedArray[0] = "orange"; // Only changes clonedArray
System.out.println(originalArray[0]); // Prints "apple"
However, if the objects themselves are modified, those changes are reflected in both arrays:
SomeObject[] originalArray = {new SomeObject(), new SomeObject()};
SomeObject[] clonedArray = originalArray.clone();
clonedArray[0].modifySomeProperty(); // Affects both arrays
clone()
for ArraysThe clone()
method is ideal when:
For a deep copy of an array containing mutable objects:
clone()
.Example of deep copy with a loop:
SomeObject[] originalArray = {new SomeObject(), new SomeObject()};
SomeObject[] deepCopiedArray = new SomeObject[originalArray.length];
for (int i = 0; i < originalArray.length; i++) {
deepCopiedArray[i] = new SomeObject(originalArray[i]); // Assumes a copy constructor
}
clone()
method is a quick way to create a shallow copy of an array.clone()
is usually sufficient.