ArrayList<ArrayList<Integer>> result = new ArrayList<>();
ArrayList<Integer> temp = new ArrayList<>();
temp.add(1);
temp.add(2);
result.add(temp);
temp.remove(temp.size() - 1);
temp.add(1, 3);
result.add(new ArrayList<>(temp));
Run Code Online (Sandbox Code Playgroud)
结果是[[1,3],[1,3]],但我认为它应该是[[1,2],[1,3]],为什么?
关注评论
temp.add(1); /aaded 1
temp.add(2); / added 2
result.add(temp);
temp.remove(temp.size() - 1); // removed index 1 that i.e removed 2
temp.add(1, 3); // added 3 at the index 1 again. now it is 1,3
result.add(new ArrayList<>(temp)); // And you are added a new array list again with temp
Run Code Online (Sandbox Code Playgroud)
如果我理解正确,你会误解逻辑
temp.add(1, 3);
Run Code Online (Sandbox Code Playgroud)
这意味着您要告诉在列表3
中的索引处添加值 .1
temp
归档时间: |
|
查看次数: |
149 次 |
最近记录: |