我如何在Java中转换ArrayList<String>对象为String[]数组?


当前回答

ArrayList<String> arrayList = new ArrayList<String>();
Object[] objectList = arrayList.toArray();
String[] stringArray =  Arrays.copyOf(objectList,objectList.length,String[].class);

使用copyOf, ArrayList to array也可以实现。

其他回答

Java 8中的替代方案:

String[] strings = list.stream().toArray(String[]::new);

Java 11 +:

String[] strings = list.toArray(String[]::new);
ArrayList<String> arrayList = new ArrayList<String>();
Object[] objectList = arrayList.toArray();
String[] stringArray =  Arrays.copyOf(objectList,objectList.length,String[].class);

使用copyOf, ArrayList to array也可以实现。

你可以为List使用toArray()方法:

ArrayList<String> list = new ArrayList<String>();

list.add("apple");
list.add("banana");

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

或者你可以手动将元素添加到数组中:

ArrayList<String> list = new ArrayList<String>();

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);
}

希望这能有所帮助!

List <String> list = ...
String[] array = new String[list.size()];
int i=0;
for(String s: list){
  array[i++] = s;
}

将任何List<Type>转换为String[]的泛型解决方案:

public static  <T> String[] listToArray(List<T> list) {
    String [] array = new String[list.size()];
    for (int i = 0; i < array.length; i++)
        array[i] = list.get(i).toString();
    return array;
}

注意:必须重写toString()方法。

class Car {
  private String name;
  public Car(String name) {
    this.name = name;
  }
  public String toString() {
    return name;
  }
}
final List<Car> carList = new ArrayList<Car>();
carList.add(new Car("BMW"))
carList.add(new Car("Mercedes"))
carList.add(new Car("Skoda"))
final String[] carArray = listToArray(carList);