Converting 'ArrayList to 'String[]' in Java

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

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

相关标签:
16条回答
  • 2020-11-22 02:32

    Starting from Java-11, one can alternatively use the API Collection.toArray(IntFunction<T[]> generator) to achieve the same as:

    List<String> list = List.of("x","y","z");
    String[] arrayBeforeJDK11 = list.toArray(new String[0]);
    String[] arrayAfterJDK11 = list.toArray(String[]::new); // similar to Stream.toArray
    
    0 讨论(0)
  • 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<String> 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.

    0 讨论(0)
  • 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<Integer> al = new ArrayList<>();
        al.add(1);
        al.add(2);
        Integer[] arr = convert(al, Integer.class);
        for (int i=0; i<arr.length; i++)
          System.out.println(arr[i]);
      }
    
      public static <T> T[] convert(ArrayList<T> al, Class clazz) {
        return (T[]) al.toArray((T[])Array.newInstance(clazz, al.size()));
      }
    }
    
    0 讨论(0)
  • 2020-11-22 02:36
    List <String> list = ...
    String[] array = new String[list.size()];
    int i=0;
    for(String s: list){
      array[i++] = s;
    }
    
    0 讨论(0)
  • 2020-11-22 02:40
    ArrayList<String> arrayList = new ArrayList<String>();
    Object[] objectList = arrayList.toArray();
    String[] stringArray =  Arrays.copyOf(objectList,objectList.length,String[].class);
    

    Using copyOf, ArrayList to arrays might be done also.

    0 讨论(0)
  • 2020-11-22 02:41
    private String[] prepareDeliveryArray(List<DeliveryServiceModel> deliveryServices) {
        String[] delivery = new String[deliveryServices.size()];
        for (int i = 0; i < deliveryServices.size(); i++) {
            delivery[i] = deliveryServices.get(i).getName();
        }
        return delivery;
    }
    
    0 讨论(0)
提交回复
热议问题