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 ArrayPrimitiveObjectConversionDemo {
    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 numbersObjects[] = ArrayUtils.toObject(numbers);
        Boolean booleansObjects[] = ArrayUtils.toObject(booleans);
        Float decimalsObjects[] = ArrayUtils.toObject(decimals);

        numbers = ArrayUtils.toPrimitive(numbersObjects);
        booleans = ArrayUtils.toPrimitive(booleansObjects);
        decimals = ArrayUtils.toPrimitive(decimalsObjects);
    }
}

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

Founder at Kode Java Org
I am a programmer, a runner, a recreational diver, currently live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. You can support my works by donating here. Thank you šŸ™‚.

Leave a Reply

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