We are going to share two ways to converting an ArrayList<String> to String array
Convert ArrayList to string array using ArrayList get() method
In this below example we are going to copying all the ArrayList<String> elements to the String Array[].
import java.util.*;
public class Main {
public static void main(String[] args) {
/* Declaration and initialization of ArrayList*/
ArrayList<String> alist= new ArrayList<String>();
alist.add("Hello");
alist.add("World");
alist.add("Java");
alist.add("Arraylist");
alist.add("Array");
/*Covering ArrayList to Array */
String str_arr[] = new String[alist.size()];
for(int j =0;j<alist.size();j++){
str_arr[j] = alist.get(j);
}
/*Print Array of elements*/
for(String s: str_arr)
{
System.out.println(s);
}
}
}
Output:-
Hello World Java Arraylist Array
Convert ArrayList to String Array in java using toArray() method
import java.util.*;
public class Main
{
public static void main(String[] args)
{
/*ArrayList declaration and initialization of ArrayList*/
ArrayList<String> string_list= new ArrayList<String>();
string_list.add("Mike");
string_list.add("John");
string_list.add("Park");
string_list.add("Robert");
string_list.add("June");
/*Converting ArrayList to Array */
String str_names[]=string_list.toArray(new String[string_list.size()]);
/*Displaying Array elements*/
for(String s: str_names)
{
System.out.println(s);
}
}
}
Output:-
Mike John Park Robert June