You have an array variable, and you want to make a clone of this array into a new array variable. To do this you can use Apache Commons Lang ArrayUtils.clone()
method. The code snippet below demonstrates the cloning of a primitive array that contains some integers elements in it.
package org.kodejava.commons.lang;
import org.apache.commons.lang3.ArrayUtils;
public class PrimitiveArrayClone {
public static void main(String[] args) {
int[] fibonacci = new int[]{1, 1, 2, 3, 5, 8, 13, 21, 34, 55};
System.out.println("fibonacci = " + ArrayUtils.toString(fibonacci));
int[] clone = ArrayUtils.clone(fibonacci);
System.out.println("clone = " + ArrayUtils.toString(clone));
}
}
The fibonacci
array contents were cloned into the clone
array, and we print out the content using ArrayUtils.toString()
method.
fibonacci = {1,1,2,3,5,8,13,21,34,55}
clone = {1,1,2,3,5,8,13,21,34,55}
In the code snippet above the clone()
method create a reference to a new array. The clone()
method itself doesn’t change the original array. In addition to clone primitive arrays the clone()
method also work for cloning array of objects.
As an example we will create an array of String
objects and clone it using the ArrayUtils.clone()
method. To display the contents of the array we will again use the ArrayUtils.toString()
method.
package org.kodejava.commons.lang;
import org.apache.commons.lang3.ArrayUtils;
public class ObjectArrayClone {
public static void main(String[] args) {
String[] colors = new String[]{"Red", "Green", "Blue", "Yellow"};
System.out.println("colors = " + ArrayUtils.toString(colors));
String[] clone = ArrayUtils.clone(colors);
System.out.println("clone = " + ArrayUtils.toString(clone));
}
}
And here is the result:
colors = {Red,Green,Blue,Yellow}
clone = {Red,Green,Blue,Yellow}
The only different between cloning a primitive array and object array using the ArrayUtils.clone()
method is that when cloning an object such as String
, Date
, etc. we need to cast the result of the clone()
method into the targeted object type.
Maven Dependencies
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
- How do I split large excel file into multiple smaller files? - April 15, 2023
- How do I get the number of processors available to the JVM? - March 29, 2023
- How do I show Spring transaction in log / console? - March 29, 2023