Java Collections - Converting to Arrays
Often, you need to create dynamic data structures that hold data and then convert them into arrays.
The Collection
interface possesses the method T[] toArray(T[] a)
. We can use this method to convert a list or other collection into an array.
By default, the toArray()
method returns an Object
array (Object[]
). If this is not what you want and you know the specific type of the array, you can provide your desired type to avoid explicit casting.
To achieve this, you need to provide the array type and an instance of that array type, like so:
List<String> list = new ArrayList<String>();
String[] stringList = (String[]) list.toArray(new String[list.size()]);
Please see more details in the Java API documentation for Collection.toArray(T[] a)
.
Enjoy Reading This Article?
Here are some more articles you might like to read next: