Given an ArrayList of String, the task is to convert the ArrayList to String array in java.
Examples:
Input: ArrayList = [ "Geeks", "for", "Geeks" ] Output: String[] = {"Geeks", "for", "Geeks"} Input: ArrayList = [ "Jupiter", "Saturn", "Uranus", "Neptune", "Sun"] Output: String[] = {"Jupiter", "Saturn", "Uranus", "Neptune", "Sun"}
- Using ArrayList.get() MethodSyntax:
str[j] = a1.get(j)
Approach:- Get the ArrayList of Strings.
- Find the size of ArrayList using size() method, and Create a String Array of this size.
- Fetch each element of the ArrayList one by one using get() method.
- Assigned each element into String Array using assignment(=) operator.
- Print String Array.
Below is the implementation of the above approach:// Java program to Convert ArrayList to// String ArrayList using get() methodimport java.util.*;public class GFG {// Function to convert ArrayList<String> to String[]public static String[] GetStringArray(ArrayList<String> arr){// declaration and initialise String ArrayString str[] = new String[arr.size()];// ArrayList to Array Conversionfor (int j = 0; j < arr.size(); j++) {// Assign each value to String arraystr[j] = arr.get(j);}return str;}// Driver codepublic static void main(String[] args){// declaration and initialise ArrayListArrayList<String>a1 = new ArrayList<String>();a1.add("Geeks");a1.add("for");a1.add("Geeks");// print ArrayListSystem.out.println("ArrayList: " + a1);// Get String ArrayString[] str = GetStringArray(a1);// Print Array elementsSystem.out.print("String Array[]: "+ Arrays.toString(str));}} - Output:
ArrayList: [Geeks, for, Geeks] String Array[]: [Geeks, for, Geeks]
Using Object array as intermediate
Syntax:Object[] arr = a1.toArray() String str = (String)obj;
Approach:- Get the ArrayList of String.
- Convert ArrayList to Object array using toArray() method.
- Iterate and convert each element to desired type using typecasting. Here it is converted to String type and added to the String Array.
- Print String Array.
No comments:
Post a Comment