Using copyOf() method:
Syntax:
Object[] gfg= a1.toArray() String[] str = Arrays.copyOf(gfg, gfg.length, String[].class);
Approach:
- Get the ArrayList of String.
- Convert ArrayList to Object array using toArray() method.
- Convert it to String Array using Arrays.copyOf() method.
- Print String Array.
// Java program to Convert ArrayList to
// String ArrayList using get() method
import java.util.*;
public class GFG {
// Function to convert ArrayList<String> to String[]
public static String[] GetStringArray(ArrayList<String> arr)
{
// Convert ArrayList to object array
Object[] objArr = arr.toArray();
// convert Object array to String array
String[] str = Arrays
.copyOf(objArr, objArr
.length,
String[].class);
return str;
}
// Driver code
public static void main(String[] args)
{
// declaration and initialise ArrayList
ArrayList<String>
a1 = new ArrayList<String>();
a1.add("Geeks");
a1.add("for");
a1.add("Geeks");
// print ArrayList
System.out.println("ArrayList: " + a1);
// Get String Array
String[] str = GetStringArray(a1);
// Print Array elements
System.out.print("String Array[]: "
+ Arrays.toString(str));
}
}
- Output:
ArrayList: [Geeks, for, Geeks] String Array[]: [Geeks, for, Geeks]
No comments:
Post a Comment