我正在尝试填充两个值对的列表。我决定在每次迭代期间使用大小为 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--;
}
关于Java - 每次迭代后重置数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59052142/