java tutorial - How to convert ArrayList to String Array in java - java programming - learn java - java basics - java for beginners



 arrlist to strarray

Learn Java - Java tutorial - arrlist to strarray - Java examples - Java programs

ArrayList to String Array

  • In this method toArray() that can convert the ArrayList of string type into the array of Strings.
  • The toArray() method without passing any argument returns Object[].
  • So you have to pass an array as an argument, which will be filled with the data from the list, and returned.
  • You can pass an empty array also, but you can pass an array with the desired size.

Syntax

            Object[] objNames = nameList.toArray();
           String[] strNames = Arrays.copyOf(objNames, objNames.length, String[].class);

Sample Code

import java.util.ArrayList;
import java.util.Arrays;
public class ArrList_to_Strarray {
    public static void main(String args[]){
        ArrayList<String> List = new ArrayList<String>();
        List.add("venkat");
        List.add("prabhu");
        List.add("kaashiv");
        Object[] obj = List.toArray();
        String[] str= Arrays.copyOf(obj, obj.length, String[].class);
        System.out.println("ArrayList converted to String array");
        for(int i=0; i < str.length; i++){
            System.out.println(str[i]);
        }
    }
}

Sample Output

       ArrayList converted to String array
                                venkat
                               prabhu
                               kaashiv

Related Searches to How to convert ArrayList to String Array in java