Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to (efficiently) convert int[] to Integer[]?

Tags:

java

Is there any direct way to convert int array to Integer array with out looping element by element.

Brute force way will be

int [] a = {1,2,3};
Integer [] b = new Integer[a.length];
for(i =0; i<a.length; i++)
    b[i]= i;

Is there any direct way with out traveling the entire array?

like image 543
javaMan Avatar asked Mar 03 '26 10:03

javaMan


1 Answers

You've found the "only" way to do it using pure Java. I prefer to make the Integer construction explicit, via

int[] a = {1,2,3};
Integer[] b = new Integer[a.length];
for (int i = 0; i < a.length; i++) {
    b[i] = Integer.valueOf(a[i]);
}

Note that Apache has some utilities in Apache Lang, which basically do the same thing; however, the call looks more like

Integer[] newArray = ArrayUtils.toObject(oldArray);

Of course, if you don't include the Apache libraries, you could write your own static function to make the code look pretty (if that's your concern).

like image 125
Edwin Buck Avatar answered Mar 05 '26 00:03

Edwin Buck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!