Convert ArrayList<String> to String[] array
To convert an ArrayList<String>
to a String[]
array in Java, you can use the toArray
method of the ArrayList class and pass it an empty array of the appropriate type:
ArrayList<String> list = new ArrayList<String>();
list.add("apple");
list.add("banana");
list.add("cherry");
String[] array = list.toArray(new String[0]);
This will create a new String[]
array with the same elements as the ArrayList.
Alternatively, you can use the toArray
method without passing it an array and then cast the result to a String[]
:
String[] array = (String[]) list.toArray();
This will also create a new String[]
array with the same elements as the ArrayList.
Keep in mind that the toArray
method returns an Object[]
array, so you will need to cast it to a String[]
if you want to use it as a String[]
array.
I hope this helps! Let me know if you have any other questions.