73

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)
Christian
  • 25,249
  • 40
  • 134
  • 225

6 Answers6

106

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.

dfa
  • 114,442
  • 31
  • 189
  • 228
jjujuma
  • 22,055
  • 12
  • 44
  • 46
20
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);


}
Paul
  • 4,812
  • 3
  • 27
  • 38
  • 2
    I also favour this version of the `toArray` method because it re-uses the parameter strarray, instead of returning a new instance – James B Mar 31 '10 at 12:17
3

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.

crazyscot
  • 11,819
  • 2
  • 39
  • 40
2

I've designed and implemented Dollar for this kind of tasks:

String[] strarray= $(strlist).toArray();
dfa
  • 114,442
  • 31
  • 189
  • 228
  • Your $ API looks great, maybe couple methods like 'sort' could accept comparators that would make it even more useful. – Greg Mar 31 '10 at 13:24
  • Thanks! Feel free to send me patches or open feature requests using bitbucket. – dfa Mar 31 '10 at 13:33
  • In order to see your implementation , I have to install 20M program to 'clone' your 254.3 KB source. – Sawyer Mar 31 '10 at 13:39
  • use the "get source" button on the right: here a link of the latest revision http://bitbucket.org/dfa/dollar/get/tip.zip – dfa Mar 31 '10 at 14:04
1

hope this can help someone out there:

List list = ..;

String [] stringArray = list.toArray(new String[list.size()]);

great answer from here: https://stackoverflow.com/a/4042464/1547266

Community
  • 1
  • 1
Arthur
  • 568
  • 7
  • 17
0
String[] strarray = strlist.toArray(new String[0]);

If you want List<String> to convert to string use StringUtils.join(slist, '\n');

cigien
  • 57,834
  • 11
  • 73
  • 112
phil
  • 620
  • 7
  • 12