Converting 'ArrayList to 'String[]' in Java

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

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

16条回答
  •  北恋
    北恋 (楼主)
    2020-11-22 02:54

    You can use the toArray() method for List:

    ArrayList list = new ArrayList();
    
    list.add("apple");
    list.add("banana");
    
    String[] array = list.toArray(new String[list.size()]);
    

    Or you can manually add the elements to an array:

    ArrayList list = new ArrayList();
    
    list.add("apple");
    list.add("banana");
    
    String[] array = new String[list.size()];
    
    for (int i = 0; i < list.size(); i++) {
        array[i] = list.get(i);
    }
    

    Hope this helps!

提交回复
热议问题