9 Years
Discussion Span
Last Post by masijade

Can anyone provide any suggestions on how to copy an ArrayList of integers to an Array?

Thank you

It is very easy u can use the toArray() method of ArrayList.

int a[]=arraylist.toArray();


Well, first of all, in an ArrayList you will have Integers, not ints (you may have added ints, but they will have been autoboxed into Integers). Secondly, you will need to tell ArrayList what type of Object[] array will be output, otherwise it will output an Object[], i.e.

Integer[] nums = intArrayList.toArray(new Integer[0]);

Once you have an Integer array, you can then use each of its elements as if it were an int, thanks to autoboxing, but if you want a real int array, you will have to create one yourself, and copy the contents from the ArrayList (or the Integer[]) into the int[] (you can, once again, let autoboxing make the conversions, but you will have to copy the elements "manually", so to say).

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.