Converting 'ArrayList to 'String[]' in Java

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

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

16条回答
  •  渐次进展
    2020-11-22 02:34

    If your application is already using Apache Commons lib, you can slightly modify the accepted answer to not create a new empty array each time:

    List list = ..;
    String[] array = list.toArray(ArrayUtils.EMPTY_STRING_ARRAY);
    
    // or if using static import
    String[] array = list.toArray(EMPTY_STRING_ARRAY);
    

    There are a few more preallocated empty arrays of different types in ArrayUtils.

    Also we can trick JVM to create en empty array for us this way:

    String[] array = list.toArray(ArrayUtils.toArray());
    
    // or if using static import
    String[] array = list.toArray(toArray());
    

    But there's really no advantage this way, just a matter of taste, IMO.

提交回复
热议问题