ArrayList<ArrayList<Integer>> list = new ArrayList<>();
int i=0;
ArrayList<Integer> l = new ArrayList<>();
l.add(1);
l.add(4);
list.add(i,l);
i++;
l.clear();
l.add(0);
l.add(4);
l.add(3);
l.add(2);
list.add(i,l);
Run Code Online (Sandbox Code Playgroud)
现在我的列表有 2 个具有相同值 {0,4,3,2} 的元素。{1,4} 会发生什么?
这是正在发生的事情。list包含对 的引用l。因此,当您清除时l,您会清除您添加到的那个list。但参考仍然存在,可以接受新的值。
ArrayList<ArrayList<Integer>> list = new ArrayList<>();
int i=0;
ArrayList<Integer> l = new ArrayList<>();
l.add(1);
l.add(4);
list.add(i,l);
i++;
l.clear(); // you just deleted all the contents of list `l` but not the list `l` itself.
l.add(0);
l.add(4);
l.add(3);
l.add(2); // now list `l` (the reference still in `list` contains 0,4,3,2
list.add(i,l); // and now list contains the same reference yet again so you get
System.out.println(list);
Run Code Online (Sandbox Code Playgroud)
印刷
[[0, 4, 3, 2], [0, 4, 3, 2]]
Run Code Online (Sandbox Code Playgroud)
请注意,如果执行此操作,list.get(0).set(1,99)将影响两个列表,因为lList 中的每个 Listlist都是对同一列表的引用。
[[0, 99, 3, 2], [0, 99, 3, 2]]
Run Code Online (Sandbox Code Playgroud)