How to convert a Java list to an array
In Java, there are many situations where a list has to be converted to an array [e.g., a function that only accepts an array as a parameter instead of a collection]. This conversion is done using the toArray[] method of the List interface.
There are two variants of this method:
1. toArray[]
This method returns an array of type Object[] whose elements are all in the same sequence as they are in the list. Casting is used to specify each elements type when performing some operations.
Code
2. toArray[T[] arr]
This variant of the same method takes an already defined array as its parameter. When the arrays size is greater than or equal to the size of the list, then the array is filled with the elements of the list. Otherwise, a new array will be created and filled up. Since the type of the returned array is specified by the parameters type, casting is unnecessary. However, ArrayStoreException is thrown if any element in the list fails to be converted into the specified type.