In this post we have shared two methods of converting an ArrayList<String> to String array.
Method 1: Manual way of conversion using ArrayList get() method
This is a manual way of copying all the ArrayList<String>
elements to the String Array[]
. In this example we have copied the whole list to array in three steps a) First we obtained the ArrayList size using size()
method b) Fetched each element of the list using get()
method and finally c) Assigned each element to corresponding array element using assignment = operator
.
package beginnersbook.com; import java.util.*; public class ArrayListTOArray { public static void main(String[] args) { /*ArrayList declaration and initialization*/ ArrayList<String> arrlist= new ArrayList<String>(); arrlist.add("String1"); arrlist.add("String2"); arrlist.add("String3"); arrlist.add("String4"); /*ArrayList to Array Conversion */ String array[] = new String[arrlist.size()]; for(int j =0;j<arrlist.size();j++){ array[j] = arrlist.get(j); } /*Displaying Array elements*/ for(String k: array) { System.out.println(k); } } }
Output:
String1 String2 String3 String4
Method2: Conversion using toArray() method
In the above example we have manually copied each element of the array list to the array. However there is a method toArray()
which can convert the ArrayList of string type to the array of Strings. More about toArray() here.
package beginnersbook.com; import java.util.*; public class Example { public static void main(String[] args) { /*ArrayList declaration and initialization*/ ArrayList<String> friendsnames= new ArrayList<String>(); friendsnames.add("Ankur"); friendsnames.add("Ajeet"); friendsnames.add("Harsh"); friendsnames.add("John"); /*ArrayList to Array Conversion */ String frnames[]=friendsnames.toArray(new String[friendsnames.size()]); /*Displaying Array elements*/ for(String k: frnames) { System.out.println(k); } } }
Output:
Ankur Ajeet Harsh John
Leave a Reply