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

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

问题描述

以下代码:

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

以这种方式写:

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

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

推荐答案

在第一种情况下,您仅创建了2个对象(两次称为 new ).您已将第二个对象添加到前三个对象中,导致第二个对象在第一个对象中出现了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.

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

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()和list.add(new ArrayList&lt;&gt;())的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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