Alex Rivera | Logout

How can I convert List<Integer> to int[] in Java?

Asked 2009-06-06T20:20:18.270
792

How can I convert a List<Integer> to int[] in Java?

I'm confused because List.toArray() actually returns an Object[], which can be cast to neither Integer[] nor int[].

Right now I'm using a loop to do so:

int[] toIntArray(List<Integer> list) {
  int[] ret = new int[list.size()];
  for(int i = 0; i < ret.length; i++)
    ret[i] = list.get(i);
  return ret;
}

Is there's a better way to do this?

This is similar to the question How can I convert int[] to Integer[] in Java?.

Edit
Report

2 Answers

5

There is really no way of "one-lining" what you are trying to do, because toArray returns an Object[] and you cannot cast from Object[] to int[] or Integer[] to int[].

answered 2009-06-06T20:33:27.293
3

Also try Dollar (check this revision):

import static com.humaorie.dollar.Dollar.*
...

List<Integer> source = ...;
int[] ints = $(source).convert().toIntArray();
answered 2010-07-05T14:40:20.453

Your Answer