Java List to Array: Complete Guide
In Java, you can use the toArray() method of the List interface to convert a list into an array. An example is shown below:
import java.util.ArrayList;
import java.util.List;
public class ListToArrayExample {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("apple");
list.add("banana");
list.add("orange");
// 将列表转换为数组
String[] array = list.toArray(new String[list.size()]);
// 打印数组中的元素
for (String element : array) {
System.out.println(element);
}
}
}
In the example above, we start by creating a list containing multiple strings, and then use the toArray() method to convert the list into a string array. The toArray() method requires passing in an array of a specified type as a parameter, so it knows what type of array to create.