Converting 'ArrayList to 'String[]' in Java

前端 未结 16 1532
情书的邮戳
情书的邮戳 2020-11-22 01:59

How might I convert an ArrayList object to a String[] array in Java?

16条回答
  •  太阳男子
    2020-11-22 02:34

    in case some extra manipulation of the data is desired, for which the user wants a function, this approach is not perfect (as it requires passing the class of the element as second parameter), but works:

    import java.util.ArrayList; import java.lang.reflect.Array;

    public class Test {
      public static void main(String[] args) {
        ArrayList al = new ArrayList<>();
        al.add(1);
        al.add(2);
        Integer[] arr = convert(al, Integer.class);
        for (int i=0; i T[] convert(ArrayList al, Class clazz) {
        return (T[]) al.toArray((T[])Array.newInstance(clazz, al.size()));
      }
    }
    

提交回复
热议问题