ArrayList to array Java

In this post we have shared two methods of converting an ArrayList to String array.

Method 1: Manual way of conversion using ArrayList get() method

This is a manual way of copying all theArrayListelements 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 arrlist= new ArrayList(); 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;jOutput:

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 methodtoArray() 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 friendsnames= new ArrayList(); 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