Convert list to array in Java
To convert a List
to an array in Java, you can use the toArray()
method of the List
interface. This method returns an array containing all of the elements in the list in the proper order.
Here's an example of how to convert a List<String>
to a String[]
array:
List<String> list = ...;
String[] array = list.toArray(new String[0]);
The toArray()
method has several overloads that allow you to specify the type and size of the array to be returned. In the example above, we passed an empty array of String
s as an argument to the toArray()
method. This creates a new array with the same runtime type and size as the list, and then fills it with the elements of the list.
If you already have an array that you want to fill with the elements of the list, you can pass that array to the toArray()
method as an argument. The method will fill the array with the elements of the list and return it. If the array is not large enough to hold all of the elements, a new array with the same runtime type and a larger size will be created and returned instead.
For example, given the following list and array:
List<String> list = Arrays.asList("apple", "banana", "cherry");
String[] array = new String[2];
You can use the following code to fill the array with the elements of the list:
array = list.toArray(array);
This will create a new array with the same runtime type and a size of 3, and fill it with the elements of the list. The original array will be discarded.
If you don't need to specify the type or size of the array, you can use the toArray()
method without arguments. This will return an array of Object
s, which you can then cast to the desired type:
List<String> list = ...;
Object[] array = list.toArray();
String[] strings = (String[]) array;
Keep in mind that this method creates a new array each time it is called, so it may not be the most efficient way to convert a list to an array if you are working with large lists. In that case, you may want to use a different method, such as the List.toArray(T[])
overload that takes an array as an argument.