How do I convert array of primitives into array of objects?

To convert from primitive arrays into object type arrays we can user Apache Commons Lang library. The commons lang provides an ArrayUtils class that does this conversion. To convert the other way just use the toPrimitive() method.

package org.kodejava.example.commons.lang;

import org.apache.commons.lang.ArrayUtils;

public class ArrayUtilsExample {
    public static void main(String[] args) {
        int numbers[] = {1, 2, 3, 4, 5};
        boolean booleans[] = {true, false, false, true};
        float decimals[] = {10.1f, 3.14f, 2.17f};

        Integer numbersObj[] = ArrayUtils.toObject(numbers);
        Boolean booleansObj[] = ArrayUtils.toObject(booleans);
        Float decimalsObj[] = ArrayUtils.toObject(decimals);
    }
}

Maven Dependencies

<!-- http://repo1.maven.org/maven2/commons-lang/commons-lang/2.6/commons-lang-2.6.jar -->
<dependency>
    <groupId>commons-lang</groupId>
    <artifactId>commons-lang</artifactId>
    <version>2.6</version>
</dependency>

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