2017  Kodetalk | Feedback | Privacy Policy | Terms | About
userimage

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

How to convert a List to int[] in Java?  because List.toArray() actually returns an Object[], which can be cast to nether Integer[] or 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;

}

please find me a better way to do this.

userimage

The easiest way to do this is to make use of Apache Commons Lang. It has a handy ArrayUtils class that can do what you want. Use the toPrimitive method with the overload for an array of Integers.

List<Integer> myList;
 ... assign and fill the list
int[] intArray = ArrayUtils.toPrimitive(myList.toArray(new Integer[myList.size()]));

This way you don't reinvent the wheel. Commons Lang has a great many useful things that Java left out. Above, I chose to create an Integer list of the right size. You can also use a 0-length static Integer array and let Java allocate an array of the right size:

static final Integer[] NO_INTS = new Integer[0];
   ....
int[] intArray2 = ArrayUtils.toPrimitive(myList.toArray(NO_INTS));


Answer is