java - 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)
我认为我的问题来自数组不是列表
解决方案
您不能使用System.arraycopy
将数据存储在不是数组的东西中。正如文档中所述:
...如果以下任何一项为真,
ArrayStoreException
则抛出 an 并且不修改目标:
src
参数引用一个不是数组的对象。dest
参数引用一个不是数组的对象。- ...
如果cols
是引用类型数组,只需使用Arrays.asList
and subList
:
columns.addAll(Arrays.asList(cols).subList(1, cols.length - 1));
推荐阅读
- python - 匹配字符串之间的正则表达式
- c# - 如何将 GitVersion /UpdateAssemblyInfo 用于尚未提交的更改?
- excel - 根据 2 个单独单元格中的值生成某些列表
- aws-lambda - 如何使用 lambda 函数来确定要转到哪个 lex bot?
- sql - 一直说我必须声明 guest_id,任何人都可以提供有关此问题的见解吗?
- wordpress - woocommerce 以编程方式重新计算价格
- php - 连接失败:连接被拒绝...来自 PHP 代码的 MySQL 数据库,但我可以从 phpmyadmin 连接
- apache - 使用网页登录svn时出现500错误
- sql-server - 为什么 SELECT 在写入更多行时不读取已提交的行?
- python - stack 期望每个张量大小相等