2

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?

javaMan
  • 5,562
  • 17
  • 57
  • 86

4 Answers4

8

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).

Edwin Buck
  • 64,804
  • 7
  • 90
  • 127
5

There's noting built in JDK but if you have apache commons, you could use

Integer[] ArrayUtils.toObject(int[] array)

Bala R
  • 101,930
  • 22
  • 186
  • 204
2

There are third-party libraries which will do the dirty work for you, but they're just going to loop under the covers.

E.g. with Guava:

int[] primitives = {1,2,3};
List<Integer> boxed = Ints.asList(primitives);
Integer[] boxedArray = Ints.asList(primitives).toArray(new Integer[]);

They don't give a one-method conversion presumably because you probably shouldn't be using arrays anyway but rather a List.

Mark Peters
  • 76,122
  • 14
  • 153
  • 186
2

That's really the only way. When you're doing b[i] = i Java is auto unboxing your int to Integer. However that doesn't work when going from an int-array to an Integer-array.

Shivan Dragon
  • 14,526
  • 9
  • 54
  • 96