Converting 'ArrayList to 'String[]' in Java

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

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

16条回答
  •  佛祖请我去吃肉
    2020-11-22 02:54

    List list = ..;
    String[] array = list.toArray(new String[0]);
    

    For example:

    List list = new ArrayList();
    //add some stuff
    list.add("android");
    list.add("apple");
    String[] stringArray = list.toArray(new String[0]);
    

    The toArray() method without passing any argument returns Object[]. So you have to pass an array as an argument, which will be filled with the data from the list, and returned. You can pass an empty array as well, but you can also pass an array with the desired size.

    Important update: Originally the code above used new String[list.size()]. However, this blogpost reveals that due to JVM optimizations, using new String[0] is better now.

提交回复
热议问题