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 integer 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 an 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.13.0</version>
</dependency>

Maven Central

How do I clone an object?

To enable our object to be cloned we need to override Object class clone method. We can also add a java.lang.Cloneable interface to our class, this interface is an empty interface. When we call the clone() method we need the add a try-catch block to catch the CloneNotSupportedException. This exception will be thrown if we tried to clone an object that doesn’t suppose to be cloned.

Calling the clone() method does a stateful, shallow copy down inside the Java Virtual Machine (JVM). It creates a new object and copies all the fields from the old object into the newly created object.

package org.kodejava.basic;

public class CloneDemo implements Cloneable {
    private int number;
    private transient int data;

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

    public static void main(String[] args) {
        CloneDemo clone = new CloneDemo();
        clone.number = 5;
        clone.data = 1000;

        try {
            // Create a clone of CloneDemo object. When we change the value of
            // number and data field in the cloned object it won't affect the
            // original object.
            CloneDemo objectClone = (CloneDemo) clone.clone();
            objectClone.number = 10;
            objectClone.data = 5000;

            System.out.println("cloned object = " + objectClone);
            System.out.println("origin object = " + clone);
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
    }

    public String toString() {
        return "[number = " + number + "; data = " + data + "]";
    }
}