Converting List<String> to String[] in Java

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)

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.


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);


}

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.