Call to ‘toArray()‘ with pre-sized array argument ‘new String[list.size()]‘问题解决

探讨了在Java中将List转换为Array的不同方法,分析了使用预设大小数组与空数组的效果差异,推荐现代Java环境下使用空数组以避免并发问题。

代码如下:
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();

评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值