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)
This question is related to
java
type-conversion
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
I've designed and implemented Dollar for this kind of tasks:
String[] strarray= $(strlist).toArray();
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.
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);
}
String[] strarray = strlist.toArray(new String[0]);
if u want List convert to string use StringUtils.join(slist, '\n');
Source: Stackoverflow.com