List转数组的方法
刷Leetcode的时候遇到一个问题:需要将一个List<String>
转换为String[]
返回。开始使用了无参数的toArray()
方法,报了类型转换异常,读了一下源码,get到了使用有参的toArray()
进行转换的方式。
Like the toArray() method, this method acts as bridge between array-based and collection-based APIs. Further, this method allows precise control over the runtime type of the output array, and may, under certain circumstances, be used to save allocation costs.
Suppose x is a list known to contain only strings. The following code can be used to dump the list into a newly allocated array of String:
String[] y = x.toArray(new String[0]);