Organizational Research By

Surprising Reserch Topic

Experts Most Trusted Topic


How to convert ArrayList to string array in 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 the ArrayList 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 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;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 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

asked Jun 11, 2015 in Java Interview Questions by rajesh
0 votes
45 views



Related Hot Questions



Walkin Jobs Opening



Government Jobs Opening


...