0

I am trying to fill a List of pair of 2 values. I decided to use an array of size 2 of fill up that array during each iteration before to place the array into the List. However, The latest array added is replacing every previous other values within the list such that: Iteration 1: [3, 7] Iteration 2: [3, 1], [3, 1] Iteration 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--;
    }

What would be the best way to fix that?

Gerard1999
  • 41
  • 3

1 Answers1

0

You are adding to the List a reference to the same array object multiple times.

You should create a new array instance in each iteration:

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--;
}
Eran
  • 387,369
  • 54
  • 702
  • 768