How do I clone an array variable?

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.example.commons.lang;

import org.apache.commons.lang.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 it self doesn’t not 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.example.commons.lang;

import org.apache.commons.lang.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 = (String[]) 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 from the when 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.

Wayan

Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. Support me by donating.

Leave a Reply