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)
We can use StringBuilder class to convert List to String. StringBuilder is the best approach if you have other than String Array, List. We can add elements in the object of StringBuilder using the append() method while looping and then convert it into string using toString() method of String class at the end.
Java String array is used to hold fixed number of Strings. String array is very common in simple java programs, specially among beginners to java and to test some specific scenarios. Even java main method argument is string array - public static void main(String[] args) .
So how to convert String array to String in java. We can use Arrays. toString method that invoke the toString() method on individual elements and use StringBuilder to create String. We can also create our own method to convert String array to String if we have some specific format requirements.
String[] and String... are the same thing internally, i. e., an array of Strings. The difference is that when you use a varargs parameter ( String... ) you can call the method like: public void myMethod( String... foo ) { // do something // foo is an array (String[]) internally System.
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With