list.add() AND list.add(new ArrayList<>()) 的区别? [英] difference on list.add() AND list.add(new ArrayList<>())?

查看:29
本文介绍了list.add() AND list.add(new ArrayList<>()) 的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码:

List>res = new ArrayList();列表<整数>行 = 新的 ArrayList<>();for (int i = 1; i <= 3; i++) {row.add(i);res.add(行);}

<块引用>

分辨率:[[1,2,3],[1,2,3],[1,2,3]]

这样写:

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

<块引用>

分辨率:[[1],[1,2],[1,2,3]]

解决方案

在第一种情况下,您只创建了 2 个对象(两次调用 new).您已将第二个添加到前 3 次,导致第二个对象在第一个中出现 3 次.

在第二种情况下,您创建了 5 个对象:res、一个工作区 rowrow 的 3 个副本3 个不同的时刻.将 3 个副本添加到 res.

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]]

解决方案

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.

这篇关于list.add() AND list.add(new ArrayList&lt;&gt;()) 的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆