Converting 'ArrayList<String> to 'String[]' in Java
You can use the toArray()
method of the ArrayList class to convert an ArrayList of strings to a string array. Here's an example:
ArrayList<String> list = new ArrayList<>();
list.add("apple");
list.add("banana");
list.add("cherry");
String[] array = list.toArray(new String[0]);
The toArray()
method takes an array of the desired type as an argument and returns an array of the same type, containing the elements of the ArrayList. In this case, we pass an empty array of strings as an argument, so the toArray()
method creates a new array of the appropriate size and fills it with the elements of the ArrayList.
You can also pass an existing array as an argument to the toArray()
method, as long as it is large enough to hold the elements of the ArrayList. If the array is too small, the toArray()
method will create a new array of the appropriate size and return it.
For example:
String[] array = new String[3];
array = list.toArray(array);
This will store the elements of the ArrayList in the array
variable, as long as it has a length of at least 3. If the array
variable has a length less than 3, a new array will be created and returned instead.