Share this page 

Convert ArrayList To a String Array Tag(s): Language


You can't convert directly an ArrayList to a String array. For example,
import java.util.List;
import java.util.ArrayList;

List<String> al = new ArrayList<String>();
al.add("a string");
String[] stringArr = new String[al.size()];
stringArr = (String []) al.toArray();
for (String s: stringArr) System.out.println("** " + s);
will throw > [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;

To make it work, you need to give to the JVM an hint about the class type involved.

The solution can be

String[] stringArr = new String[al.size()];
stringArr = al.toArray(stringArr);  // give the target array as parameter to
                                    // to inform the JVM that we are using
                                    // a String array
for (String s: stringArr) System.out.println("** " + s);
or
String[] stringArr = al.toArray(new String[] {});
for (String s: stringArr) System.out.println("** " + s);

In Java 8,

import java.util.List;
import java.util.ArrayList;

public class ArrayTest {
   public static void main(String[] args) {
      List<String> al = new ArrayList<String>();
      al.add("a string");
      String[] stringArr = al.stream().toArray(String[]::new); // using Java 8 streams
      for (String s: stringArr) System.out.println("** " + s);
   }
}

mail_outline
Send comment, question or suggestion to howto@rgagnon.com