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);

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

The output of our code snippet:


Maven Dependencies


Maven Central


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.