java - Java - 每次迭代后重置数组
问题描述
我正在尝试填充一对 2 值的列表。我决定在每次迭代期间使用一个大小为 2 的数组来填充该数组,然后再将该数组放入列表中。但是,添加的最新数组正在替换列表中的所有其他值,例如:迭代 1:[3, 7]
迭代 2:[3, 1], [3, 1]
迭代 3:[2, 5], [2, 5], [2, 5]
List<int[]> preLCSOne = new ArrayList<>();
int[] temp = new int[2];
int i = 0;
while (LCSuff[row][col] != 0) {
temp[0] = X.get(row - 1).getLine();
temp[1] = X.get(row - 1).getCharPositionInLine();
preLCSOne.add(temp);
i++;
--len;
row--;
col--;
}
解决这个问题的最佳方法是什么?
解决方案
您正在List
多次添加对同一数组对象的引用。
您应该在每次迭代中创建一个新的数组实例:
List<int[]> preLCSOne = new ArrayList<>();
int i = 0;
while (LCSuff[row][col] != 0) {
int[] temp = new int[2];
temp[0] = X.get(row - 1).getLine();
temp[1] = X.get(row - 1).getCharPositionInLine();
preLCSOne.add(temp);
i++;
--len;
row--;
col--;
}
推荐阅读
- c# - 基于颜色的 WPF DataTrigger
- google-cloud-platform - 使用 bq CLI 在 bigquery 中列出数据集中的所有表并将它们存储到谷歌云存储
- c++ - clang:候选模板被忽略:替换失败:typedef'type'不能用类说明符引用
- rabbitmq - Ansible 没有使用 rabbitmq_user 模块创建 RabbitMQ 用户
- java - 如何将对象中的多个字段与对象队列进行比较?
- javascript - 将 var 声明(例如 var x;)覆盖以前的值
- java - 如何从 Java Play 框架中的动作返回结果?
- google-drive-api - 如何从谷歌绘图中提取文本?
- vue.js - 我不能在 Vue.js 中使用计算的 GroupBy 数组
- mysql - 我无法查看我刚刚创建的表格?我不知道为什么