How do I convert array of object to 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 array of Integer objects this method is overloadded to accept other types of object array.

package org.kodejava.example.commons.lang;

import org.apache.commons.lang.ArrayUtils;

public class ObjectArrayToPrimitiveDemo {

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

        // Convert array of integer objects to a primitive array of type int
        int[] fibbos = ArrayUtils.toPrimitive(integers);

Wayan Saryada

Programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.

Leave a Reply