How might I convert an ArrayList
object to a String[]
array in Java?
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 al = new ArrayList<>();
al.add(1);
al.add(2);
Integer[] arr = convert(al, Integer.class);
for (int i=0; i T[] convert(ArrayList al, Class clazz) {
return (T[]) al.toArray((T[])Array.newInstance(clazz, al.size()));
}
}