Converting List<String> to String[] in Java
JavaType ConversionJava Problem Overview
How do I convert a list of String into an array? The following code returns an error.
public static void main(String[] args) {
List<String> strlist = new ArrayList<String>();
strlist.add("sdfs1");
strlist.add("sdfs2");
String[] strarray = (String[]) strlist.toArray();
System.out.println(strarray);
}
Error:
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;
at test.main(test.java:10)
Java Solutions
Solution 1 - Java
You want
String[] strarray = strlist.toArray(new String[0]);
See here for the documentation and note that you can also call this method in such a way that it populates the passed array, rather than just using it to work out what type to return. Also note that maybe when you print your array you'd prefer
System.out.println(Arrays.toString(strarray));
since that will print the actual elements.
Solution 2 - Java
public static void main(String[] args) {
List<String> strlist = new ArrayList<String>();
strlist.add("sdfs1");
strlist.add("sdfs2");
String[] strarray = new String[strlist.size()]
strlist.toArray(strarray );
System.out.println(strarray);
}
Solution 3 - Java
List.toArray()
necessarily returns an array of Object. To get an array of String, you need to use the casting syntax:
String[] strarray = strlist.toArray(new String[0]);
See the javadoc for java.util.List for more.
Solution 4 - Java
I've designed and implemented Dollar for this kind of tasks:
String[] strarray= $(strlist).toArray();
Solution 5 - Java
hope this can help someone out there:
List
String [] stringArray = list.toArray(new String[list.size()]);
great answer from here: https://stackoverflow.com/a/4042464/1547266
Solution 6 - Java
String[] strarray = strlist.toArray(new String[0]);
if u want List