4

the following code:

List<List<Integer>> res = new ArrayList<>();
List<Integer> row = new ArrayList<>();

for (int i = 1; i <= 3; i++) {
  row.add(i);
  res.add(row);
}

res: [[1,2,3],[1,2,3],[1,2,3]]

wrote in this way:

for (int i = 1; i <= 3; i++) {
  row.add(i);
  res.add(new ArrayList<>(row));
}

res: [[1],[1,2],[1,2,3]]

Peter
  • 155
  • 2
  • 10

1 Answers1

4

In the first case, you've only create 2 objects (called new twice). You've added the second to the first 3 times, resulting in the second object appearing 3 times in the first.

In the second case, you've created 5 objects: res, a work area row, and 3 copies of row taken a 3 different moments in time. The 3 copies are added to res.

AJNeufeld
  • 8,526
  • 1
  • 25
  • 44