Java Collection How to - Convert list into an array








Question

We would like to know how to convert list into an array.

Answer

public Object[] toArray()
public Object[] toArray(Object[] a)

The first toArray() method returns an Object array. The second version returns an array of a specific type, Object or otherwise.

import java.util.Arrays;
import java.util.List;
/* w w  w  .  j  av a2 s  .  c  o m*/
public class MainClass {
  public static void main(String[] a) {
    List list = Arrays.asList(new String[] { "A", "B", "C", "D" });

    Object[] objArray = list.toArray();

    for (Object obj : objArray) {
      System.out.println(obj);
    }

    String[] strArray = (String[]) list.toArray(new String[list.size()]);

    for (String string : strArray) {
      System.out.println(string);
    }
  }
}

The code above generates the following result.