Java Array Clone
Many times, we need to clone an array to backup the original elements of it. We have some special strings and numbers like palindrome number, palindrome string, and Armstrong number, and to check their specialty, we need to clone the array. For example, to check whether a string is a palindrome or not, we first convert a string into a character array and clone the char array as a temp. Now, we reverse the elements of the char array and compare it with the temp that contains the original string.
In simple words, we need to clone the array when we want to back up the original data. In Java, we have four ways to clone an array which are as follows:
By Copying Array Elements
It is the naive way to clone an array. In this method, we iterate the original array and put each element of the array into another array. We clone the array by copying elements in the following way:
Using clone() Method
In the above method, we have iterated the original array to make a clone of it. We have another way that takes less time to clone the given array, i.e., the clone() method of the Object class. The syntax of the clone() method is as follwos:
Let's implement the code to clone an array by using Object's clone() method:
Using arraycopy() Method
Just like the clone() method, we can also use the arraycopy() method of the System class available in the java.lang package. The arraycopy() method has the following syntax:
Here, src defines the source array, srcPos defines the index from where copying should be started, dest defines the array in which elements will be copied, destPos defines the index from which the copied elements are placed in the clone array, and length is the size of the subarray to be copied.
Let's implement the code to clone an array by using the System.arraycopy() method:
Using copyOf() Method
Just like clone() and arraycopy() methods, we can also use copyOf() method of the Arrays class available in the java.util package. The copyOf () method has the following syntax:
Here, arr defines the original array, and len is the length of the array to get copied.
Let's implement the code to clone an array by using arraycopy() method of Arrays class:
Using copyOfRange() Method
Lust like copyOf() method, Arrays class provide copyOfRange() method to clone an array. The copyOfRange() method is used to copy the elements of the specified range of the original array into clone array. The syntax of the copyOfRange() method is as follows:
Here, the original defines the original array, from defines initial index and to defines the final index of the element.
Let's implement the code to clone an array by using arraycopyRange() method of Arrays class:
All the above-discussed ways are used for cloning an array. We recommend you to use the clone() method of the Object class to clone the array.