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);}
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()));}}
List<String> list = ..;String[] array = list.toArray(ArrayUtils.EMPTY_STRING_ARRAY);
// or if using static importString[] array = list.toArray(EMPTY_STRING_ARRAY);
ArrayUtils中还有一些不同类型的预分配空数组。
我们还可以通过这种方式欺骗JVM为我们创建一个空数组:
String[] array = list.toArray(ArrayUtils.toArray());
// or if using static importString[] array = list.toArray(toArray());
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