Java - 声纳 - 不应使用循环复制数组

Java - Sonar - Arrays should not be copied using loops

我的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);
        }

    }

}

Sonar 说:不应使用循环复制数组

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

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

所以,我试试这个:

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)

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

是这样的吗?

columns = Arrays.asList(Arrays.copyOfRange(col, 1, col.length));

或这个

columns.addAll(Arrays.asList(Arrays.copyOfRange(col, 1, col.length )));

您不能使用 System.arraycopy 将数据存储在非数组的内容中。正如它所说 in the documentation:

... if any of the following is true, an ArrayStoreException is thrown and the destination is not modified:

  • The src argument refers to an object that is not an array.
  • The dest argument refers to an object that is not an array.
  • ...

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

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