I'm trying to convert an ArrayList containing Integer objects to primitive int[] with the following piece of code, but it is throwing compile time error. Is it possible to convert in Java?
List<Integer> x = new ArrayList<Integer>();
int[] n = (int[])x.toArray(int[x.size()]);
Apache Commons has a ArrayUtils class, which has a method toPrimitive() that does exactly this.
However, as Jon showed, it is pretty easy to do this by yourself instead of using external libraries.
You can convert, but I don't think there's anything built in to do it automatically:
(Note that this will throw a NullPointerException if either
integers
or any element within it isnull
.)EDIT: As per comments, you may want to use the list iterator to avoid nasty costs with lists such as
LinkedList
:Google Guava
Google Guava provides a neat way to do this by calling
Ints.toArray
.This code segment is working for me, try this
access
arr
like normalint[]
.It bewilders me that we encourage one-off custom methods whenever a perfectly good, well used library like Apache Commons has solved the problem already. Though the solution is trivial if not absurd, it is irresponsible to encourage such a behavior due to long term maintenance and accessibility.
Just go with Apache Commons