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]);
在LeetCode中解决编程问题时,遇到了将List<String>转换为String[]的需求。初始尝试使用了List的toArray()方法,但遇到了类型转换异常。通过阅读源码,了解到可以使用有参的toArray()方法,如`String[] y = x.toArray(new String[0]);`来避免类型转换错误,这种方法在特定情况下还能节省内存分配成本。
1万+

被折叠的 条评论
为什么被折叠?



