To convert from primitive arrays into object type arrays, we can use the 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.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 Dependencies
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.14.0</version>
</dependency>
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024