[英]What's the difference between these two java arrayList.add()
public void findCombination(List<List<Integer>> ans, ArrayList<Integer> tmp, int [] candidates, int remain, int start){
if(remain < 0){
return ;
}
else if(remain == 0){
ans.add(new ArrayList<>(tmp));
}
else{
for(int i = start; i < candidates.length; i++){
tmp.add(candidates[i]);
findCombination(ans, tmp, candidates, remain-candidates[i], i);
tmp.remove(tmp.size()-1);
}
}
}
在上面的代码中,我发现将ans.add(new ArrayList<>(tmp))
更改为ans.add(tmp)
。 它不起作用...所以我想问,为什么? ans.add(new ArrayList<>(tmp))
和ans.add(tmp)
之间有什么区别?
区别在于,当您使用ans.add(new ArrayList<>(tmp))
您将创建列表tmp
的副本,而不是将其添加到列表中。
如果使用ans.add(tmp)
添加它,则对列表tmp
所做的任何更改都将反映在您放置在列表中的列表中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.