Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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) 
like image 590
Christian Avatar asked Mar 31 '10 11:03

Christian


People also ask

How do I convert a List to a String in Java?

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.

What is String [] [] in Java?

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

Can we convert String [] to String?

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.

Is String and String [] same in Java?

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.


2 Answers

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.

like image 139
jjujuma Avatar answered Sep 21 '22 19:09

jjujuma


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);   } 
like image 41
Paul Avatar answered Sep 21 '22 19:09

Paul