How might I convert an ArrayList
object to a String[]
array in Java?
Generics solution to covert any List
to String []
:
public static String[] listToArray(List list) {
String [] array = new String[list.size()];
for (int i = 0; i < array.length; i++)
array[i] = list.get(i).toString();
return array;
}
Note You must override toString()
method.
class Car {
private String name;
public Car(String name) {
this.name = name;
}
public String toString() {
return name;
}
}
final List carList = new ArrayList();
carList.add(new Car("BMW"))
carList.add(new Car("Mercedes"))
carList.add(new Car("Skoda"))
final String[] carArray = listToArray(carList);