Java如何将对象数组转换为原始数组?

在下面的代码示例中,我们演示了ArrayUtils.toPrimitive()将Integer对象的数组转换为其原始类型的数组的方法。除了转换Integer对象的数组之外,此方法也可以重载以接受其他类型的对象数组。

package org.nhooo.example.commons.lang;

import org.apache.commons.lang3.ArrayUtils;

public class ArrayObjectToPrimitiveDemo {
    public static void main(String[] args) {
        // 整数对象数组。
        Integer[] integers = {1, 2, 3, 5, 8, 13, 21, 34, 55};
        Boolean[] booleans = {Boolean.TRUE, Boolean.TRUE, Boolean.FALSE, Boolean.FALSE};

        // 将Integer对象的数组转换为int类型的数组。
        int[] ints = ArrayUtils.toPrimitive(integers);
        System.out.println(ArrayUtils.toString(ints));

        // 将布尔对象数组转换为布尔类型的数组。
        boolean[] bools = ArrayUtils.toPrimitive(booleans);
        System.out.println(ArrayUtils.toString(bools));
    }
}

我们的代码片段的输出:

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

Maven依赖

<!-- https://search.maven.org/remotecontent?filepath=org/apache/commons/commons-lang3/3.9/commons-lang3-3.9.jar -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.9</version>
</dependency>

Maven中央