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()]);
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
integersor 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: