In the code example below we demonstrate the ArrayUtils.toPrimitive()
method to convert an array of Integer object to an array of its primitive type. Besides converting an array of Integer objects, this method is overloaded to accept other types of object’s array.
package org.kodejava.commons.lang;
import org.apache.commons.lang3.ArrayUtils;
public class ArrayObjectToPrimitiveDemo {
public static void main(String[] args) {
// An array of Integer objects.
Integer[] integers = {1, 2, 3, 5, 8, 13, 21, 34, 55};
Boolean[] booleans = {Boolean.TRUE, Boolean.TRUE, Boolean.FALSE, Boolean.FALSE};
// Convert and array of Integer objects into an array of type int.
int[] ints = ArrayUtils.toPrimitive(integers);
System.out.println(ArrayUtils.toString(ints));
// Convert an array of Boolean objects into an array of type boolean.
boolean[] bools = ArrayUtils.toPrimitive(booleans);
System.out.println(ArrayUtils.toString(bools));
}
}
The output of our code snippet:
{1,2,3,5,8,13,21,34,55}
{true,true,false,false}
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 use Proxy class to configure HTTP and SOCKS proxies in Java? - March 27, 2025
- How do I retrieve network interface information using NetworkInterface in Java? - March 26, 2025
- How do I work with InetAddress to resolve IP addresses in Java? - March 25, 2025