zoukankan      html  css  js  c++  java
  • Warning: Call to 'toArray()' with pre-sized array argument 'new String[list.size()]'

    当使用如下代码将List转换为Array类型时:

    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]).

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

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

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

    List<String> list = new ArrayList<>();
    String[] array = list.toArray(new String[0]);

    参考:https://blog.csdn.net/QasimCyrus/article/details/88674516

  • 相关阅读:
    edgeR
    R中的运算符,条件语句,控制语句
    library-type:fr-unstanded vs fisrt-stand vs second-stanrd
    R的几个基础函数
    HTseq-count
    HISAT2的运用
    shell的符号总结
    python-tuple
    python -List
    win10 ubuntu18.0 LTS双系统安装
  • 原文地址:https://www.cnblogs.com/MK-XIAOYU/p/10666096.html
Copyright © 2011-2022 走看看