Java Convert int[] to Integer[] example
By:Roy.LiuLast updated:2019-08-17
Examples show you how to convert between int[] and its’ wrapper class Integer[].
1. Convert int[] to Integer[]
public static Integer[] toObject(int[] intArray) { Integer[] result = new Integer[intArray.length]; for (int i = 0; i < intArray.length; i++) { result[i] = Integer.valueOf(intArray[i]); return result;
2. Convert Integer[] to int[]
public static int[] toPrimitive(Integer[] IntegerArray) { int[] result = new int[IntegerArray.length]; for (int i = 0; i < IntegerArray.length; i++) { result[i] = IntegerArray[i].intValue(); return result;
The theory is simple, create a new array, and dump the old value inside.
1. Full Example
Review a full example to show you how it works.
ArrayConvertExample.java
package com.mkyong.test; public class ArrayConvertExample { public static void main(String[] args) { int[] obj = new int[] { 1, 2, 3 }; Integer[] newObj = toObject(obj); System.out.println("Test toObject() - int -> Integer"); for (Integer temp : newObj) { System.out.println(temp); Integer[] obj2 = new Integer[] { 4, 5, 6 }; int[] newObj2 = toPrimitive(obj2); System.out.println("Test toPrimitive() - Integer -> int"); for (int temp : newObj2) { System.out.println(temp); // Convert int[] to Integer[] public static Integer[] toObject(int[] intArray) { Integer[] result = new Integer[intArray.length]; for (int i = 0; i < intArray.length; i++) { result[i] = Integer.valueOf(intArray[i]); return result; // Convert Integer[] to int[] public static int[] toPrimitive(Integer[] IntegerArray) { int[] result = new int[IntegerArray.length]; for (int i = 0; i < IntegerArray.length; i++) { result[i] = IntegerArray[i].intValue(); return result;
Output
Test toObject() - int -> Integer Test toPrimitive() - Integer -> int
2. ArrayUtils Example
To save you time, uses the ArrayUtils class from the Apache common library, it does the same thing.
ArrayConvertExample.java
package com.mkyong.test; import org.apache.commons.lang3.ArrayUtils; public class ArrayConvertExample { public static void main(String[] args) { int[] obj = new int[] { 1, 2, 3 }; Integer[] newObj = ArrayUtils.toObject(obj); System.out.println("Test toObject() - int -> Integer"); for (Integer temp : newObj) { System.out.println(temp); Integer[] obj2 = new Integer[] { 4, 5, 6 }; int[] newObj2 = ArrayUtils.toPrimitive(obj2); System.out.println("Test toPrimitive() - Integer -> int"); for (int temp : newObj2) { System.out.println(temp);
Test toObject() - int -> Integer Test toPrimitive() - Integer -> int
References
From:一号门
COMMENTS