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 print the contents of an array variable?

You need to print the contents of an array variable. The long way to it is to user a loop to print each element of the array. To simplify this, you can use the Apache Commons Lang ArrayUtils.toString() method. This method can take any array as a parameter and print out the contents separated by commas and surrounded by curly brackets. When you need to print a specific string when the array is null, you can provide the second string argument to this method.

package org.kodejava.commons.lang;

import org.apache.commons.lang3.ArrayUtils;

public class ArrayUtilsToString {
    public static void main(String[] args) {
        // Print an int array as string.
        int[] numbers = {1, 2, 3, 5, 8, 13, 21, 34};
        System.out.println("Numbers = " + ArrayUtils.toString(numbers));

        // Print string array as string.
        String[] grades = {"A", "B", "C", "D", "E", "F"};
        System.out.println("Grades = " + ArrayUtils.toString(grades));

        // Print a multidimensional array as string.
        int[][] matrix = {{0, 1, 2}, {1, 2, 3}, {2, 3, 4}};
        System.out.println("Matrix = " + ArrayUtils.toString(matrix));

        // Return "Empty" when the array is null.
        String[] colors = null;
        System.out.println("Colors = " + ArrayUtils.toString(colors, "None"));
    }
}

The output of the code snippet above:

Numbers = {1,2,3,5,8,13,21,34}
Grades = {A,B,C,D,E,F}
Matrix = {{0,1,2},{1,2,3},{2,3,4}}
Colors = None

If you are using the JDK 1.5, or later, you can actually use the java.util.Arrays class to do the same thing as the org.apache.commons.lang.ArrayUtils class does.

Maven Dependencies

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.13.0</version>
</dependency>

Maven Central

How do I find specific elements or object in an array?

This example demonstrates how to find specific items in an array. We will use the org.apache.commons.lang3.ArrayUtils class. This class provides method called contains(Object[] array, Object objectToFind) method to check if an array contains the objectToFind in it.

We can also use the indexOf(Object[] array, Object objectToFind) method and the lastIndexOf(Object[] array, Object objectToFind) method to get the index of an array element where our objectToFind is located.

package org.kodejava.commons.lang;

import org.apache.commons.lang3.ArrayUtils;

public class ArrayUtilsIndexOfDemo {
    public static void main(String[] args) {
        String[] colors = { "Red", "Orange", "Yellow", "Green",
                "Blue", "Violet", "Orange", "Blue" };

        // Does the "colors" array contain the Blue color?
        boolean contains = ArrayUtils.contains(colors, "Blue");
        System.out.println("Contains Blue? " + contains);

        // Can you tell me the index of each color defined bellow?
        int indexOfYellow = ArrayUtils.indexOf(colors, "Yellow");
        System.out.println("indexOfYellow = " + indexOfYellow);

        int indexOfOrange = ArrayUtils.indexOf(colors, "Orange");
        System.out.println("indexOfOrange = " + indexOfOrange);

        int lastIndexOfOrange = ArrayUtils.lastIndexOf(colors, "Orange");
        System.out.println("lastIndexOfOrange = " + lastIndexOfOrange);
    }
}

Here are the results of the code above.

Contains Blue? true
indexOfYellow = 2
indexOfOrange = 1
lastIndexOfOrange = 6

Maven Dependencies

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.13.0</version>
</dependency>

Maven Central

How do I convert an array of object to an array of primitive?

In the code example below we demonstrate the ArrayUtils.toPrimitive() method to convert an array of Integer object to an array of its primitive type. Besides converting an array of Integer objects, this method is overloaded to accept other types of object’s array.

package org.kodejava.commons.lang;

import org.apache.commons.lang3.ArrayUtils;

public class ArrayObjectToPrimitiveDemo {
    public static void main(String[] args) {
        // An array of Integer objects.
        Integer[] integers = {1, 2, 3, 5, 8, 13, 21, 34, 55};
        Boolean[] booleans = {Boolean.TRUE, Boolean.TRUE, Boolean.FALSE, Boolean.FALSE};

        // Convert and array of Integer objects into an array of type int.
        int[] ints = ArrayUtils.toPrimitive(integers);
        System.out.println(ArrayUtils.toString(ints));

        // Convert an array of Boolean objects into an array of type boolean.
        boolean[] bools = ArrayUtils.toPrimitive(booleans);
        System.out.println(ArrayUtils.toString(bools));
    }
}

The output of our code snippet:

{1,2,3,5,8,13,21,34,55}
{true,true,false,false}

Maven Dependencies

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.13.0</version>
</dependency>

Maven Central

How do I convert an array to a Map?

This example uses the Apache Commons Lang’s ArrayUtils.toMap() method to convert a two-dimensional array into a Map object.

To convert a two-dimensional array into a Map object, each element of the two-dimensional array must be an array with at least two elements where the first element will be the key and the second element will be the value.

package org.kodejava.commons.lang;

import java.util.Map;

import org.apache.commons.lang3.ArrayUtils;

public class ArrayToMapExample {

    public static void main(String[] args) {
        // A two-dimensional array of country capital.
        String[][] countries = {{"United States", "Washington, D.C."},
                {"United Kingdom", "London"},
                {"Netherlands", "Amsterdam"},
                {"Japan", "Tokyo"},
                {"France", "Paris"}};

        // Convert an array to a Map.
        Map<Object, Object> capitals = ArrayUtils.toMap(countries);
        for (Object key : capitals.keySet()) {
            System.out.printf("%s is the capital of %s.%n", capitals.get(key), key);
        }
    }
}

The result of our code snippet:

London is the capital of United Kingdom.
Amsterdam is the capital of Netherlands.
Paris is the capital of France.
Washington, D.C. is the capital of United States.
Tokyo is the capital of Japan.

Maven Dependencies

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.13.0</version>
</dependency>

Maven Central