How to Convert a List to an Array in Java
To convert a List to an array in Java, you can use either of the following methods:
Foo[] array = list.toArray(new Foo[0]);
Foo[] array = new Foo[list.size()]; list.toArray(array);
These methods only work for arrays of reference types. For primitive type arrays, you must use the traditional approach:
List<Integer> list = ...; int[] array = new int[list.size()]; for(int i = 0; i < list.size(); i++) array[i] = list.get(i);
Best Practice
It is recommended to use the first method, list.toArray(new Foo[0]), for converting lists to arrays. This eliminates the need to specify the size of the array in advance and is more efficient in modern Java.
The above is the detailed content of How Do I Convert a Java List to an Array?. For more information, please follow other related articles on the PHP Chinese website!