首页 > 解决方案 > Java - 声纳 - 不应使用循环复制数组

问题描述

我的java代码:

public class TestArray {

    public static void main(String[] args) {

        final String[] cols = { "a", "b", "c", "d" };
        List<String> columns = new ArrayList<>(4);

        // for (int i = 1; i < cols.length - 1; i++) {
        // columns.add(cols[i]);
        // }
        System.arraycopy(cols, 0, columns, 0, cols.length - 1);

        for (String c : columns) {
            System.out.println(c);
        }

    }

}

声纳说:不应该使用循环复制数组

当有内置函数可以为您完成时,使用循环复制数组或数组的子集只是浪费代码。相反,使用 Arrays.copyOf 将整个数组复制到另一个数组中,使用 System.arraycopy 仅将数组的子集复制到另一个数组中,并使用 Arrays.asList 为新列表的构造函数提供数组。

请注意,Arrays.asList 只是在原始数组周围放置一个 Collections 包装器,因此如果需要非固定大小的 List,则需要进一步的步骤。

所以,我试试这个:

System.arraycopy(cols, 1, columns, 0, cols.length -1);

我有这个错误:

Exception in thread "main" java.lang.ArrayStoreException
    at java.lang.System.arraycopy(Native Method)
    at com.company.TestArray.main(TestArray.java:16)

我认为我的问题来自数组不是列表

标签: javaarrayssonarqube

解决方案


您不能使用System.arraycopy将数据存储在不是数组的东西中。正如文档中所述

...如果以下任何一项为真,ArrayStoreException则抛出 an 并且不修改目标:

  • src参数引用一个不是数组的对象。
  • dest参数引用一个不是数组的对象。
  • ...

如果cols是引用类型数组,只需使用Arrays.asListand subList

columns.addAll(Arrays.asList(cols).subList(1, cols.length - 1));

推荐阅读