问题
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]]
回答1:
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
.
来源:https://stackoverflow.com/questions/45929473/difference-on-list-add-and-list-addnew-arraylist