75

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)
2
  • 1
    For most questions with an error, you should post up the error message that you are receiving. Commented Mar 31, 2010 at 12:01
  • 1
    I like stackoverflow more. Thanks for ranking 1 in google. Commented Apr 7, 2013 at 0:57

6 Answers 6

107

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Using strlist.toArray(new String[strlist.size()]); is usually more efficient.
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);


}

1 Comment

I also favour this version of the toArray method because it re-uses the parameter strarray, instead of returning a new instance
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.

Comments

2

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

String[] strarray= $(strlist).toArray();

4 Comments

Your $ API looks great, maybe couple methods like 'sort' could accept comparators that would make it even more useful.
Thanks! Feel free to send me patches or open feature requests using bitbucket.
In order to see your implementation , I have to install 20M program to 'clone' your 254.3 KB source.
use the "get source" button on the right: here a link of the latest revision bitbucket.org/dfa/dollar/get/tip.zip
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

Comments

0
String[] strarray = strlist.toArray(new String[0]);

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.