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

Thank you

Re: Arrays and ArrayList 80 80

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();

Re: Arrays and ArrayList 80 80

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).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.18 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.