首页 > 解决方案 > 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--;
    }

解决这个问题的最佳方法是什么?

标签: java

解决方案


您正在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--;
}

推荐阅读