How to convert List of Integers to int array in Java - Coding Tips

So, you have a List of Integers and you want to convert them into int array? Yes you read it write, not on Integer array but int array. Though in most practical purpose, Integer array can be used in place of int[] because ofautoboxing in Java, you still need an int[] if your method accepts it. In Java, you can not type cast an Integer array into int array. Many Java programmer think about toArray() method from java.util.List to convert a List into Array, but unfortunately toArray() is useless in most of times. It doesn't allow you to convert List into primitive arrays. Though you can convert List of Integers to array of Integers, but not array of primitive int. This is true for List of all wrapper class e.g. List of Float, Double, Long, toArray() method can return array of wrapper class but not primitives. After looking into Java Collection API, It seems that only traditional for loop or foreach can help, which involves iterating over Integer arrayand storing them into int[], but fortunately, I came across Apache Commons ArrayUtils class. ArrayUtils can do this work for us, It has several overloaded methods to convert Object arrays into primitive arrays. For example, you can convert an array of Double i.e. Double[] to primitive double array e.g. double[]. This example once again reinforced my thinking to include Apache Commons lang and Google's Guava by default in any Java project, they are rich and effectively complement standard JDK library.
Read more »

0 Response to "How to convert List of Integers to int array in Java - Coding Tips"

Posting Komentar