difference on list.add() AND list.add(new ArrayList<>())? [duplicate]

风格不统一 提交于 2021-02-07 18:07:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!