Java如何将原始数组转换为对象数组?
要将原始数组转换为对象类型数组,我们可以使用ApacheCommonsLang库。commonslang提供了一个进行ArrayUtils此转换的类。要转换为其他方式,只需使用toPrimitive()方法。
package org.nhooo.example.commons.lang; import org.apache.commons.lang3.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依赖
<!-- 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>