代码如下:
List list = new ArrayList<>();
String[] array = list.toArray(new String[list.size()]);
这样转换时会报错:
Call to ‘toArray()’ with pre-sized array argument ‘new String[list.size()]’
Inspection info: There are two styles to convert a collection to an array: either using a pre-sized array (like c.toArray(new String[c.size()])) or using an empty array (like c.toArray(new String[0]).
In older Java versions using pre-sized array was recommended, as the reflection call which is necessary to create an array of proper size was quite slow. However since late updates of OpenJDK 6 this call was intrinsified, making the performance of the empty array version the same and sometimes even better, compared to the pre-sized version. Also passing pre-sized array is dangerous for a concurrent or synchronized collection as a data race is possible between the size and toArray call which may result in extra nulls at the end of the array, if the collection was concurrently shrunk during the operation.
This inspection allows to follow the uniform style: either using an empty array (which is recommended in modern Java) or using a pre-sized array (which might be faster in older Java versions or non-HotSpot based JVMs).
在低版本的 Java 中推荐使用初始化大小的数组,因为使用反射调用去创建一个合适大小的数组相对较慢。但是在 openJDK 6 之后的高版本中方法被优化了,传入空数组相比传入初始化大小的数组,效果是相同的甚至有时候是更优的。因为使用 concurrent 或 synchronized 集合时,如果集合进行了收缩,toArray()和size()方法可能会发生数据竞争,此时传入初始化大小的数组是危险的。
可以改成:
List list = new ArrayList<>();
String[] array = list.toArray(new String[0]);
或者:
List list = new ArrayList<>();
String[] array = (String[])list.toArray();
探讨了在Java中将List转换为Array的不同方法,分析了使用预设大小数组与空数组的效果差异,推荐现代Java环境下使用空数组以避免并发问题。
7176





