Android Studio检查警告:Call to 'toArray()' with pre-sized array argument 'new String[list.size()]'

当使用如下代码将集合转成数组时:

List<String> 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).

转换集合为数组的时候,有两种方式:使用初始化大小的数组(这里指的是初始化大小的时候使用了集合的size()方法)和空数组。

在低版本的 Java 中推荐使用初始化大小的数组,因为使用反射调用去创建一个合适大小的数组相对较慢。但是在 openJDK 6 之后的高版本中方法被优化了,传入空数组相比传入初始化大小的数组,效果是相同的甚至有时候是更优的。因为使用 concurrent 或 synchronized 集合时,如果集合进行了收缩,toArray()size()方法可能会发生数据竞争,此时传入初始化大小的数组是危险的。

因此在高版本的 Java 上面可以改为:

List<String> list = new ArrayList<>();
String[] array = list.toArray(new String[0]);
  • 13
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值