今天做题时遇到一个比较简单的题,却翻车了,调试了许久没有找到错误原因,输出结果一直为空


忽然我灵光一闪,会不会是这个add的方法有问题呢,毕竟代码逻辑并没有什么错误。
于是我查了会资料却并没有什么收获……
无意中一瞥看见了一个搜索栏add方法时是拷贝的引用还是值。我忽然悟了,很快啊,

我左一个集合,右一个集合套集合,然后一运行,哈,还真是
public static void main(String[] args) {
ArrayList<Integer>list = new ArrayList<>();
ArrayList<ArrayList<Integer>>result = new ArrayList<>();
result.add(list);
for(int i = 0; i < 5; i++){
list.add(i);
System.out.println("待选结果"+list);
System.out.println("结果集:"+result);
System.out.println("========================");
}
}

我们可以清楚的看到我们事先就把list已经添加到了result中,但是list中添加元素后,result中元素也改变了 ,这说明add传入的是list的引用,而不是值。
public static void main(String[] args) {
ArrayList<Integer>list = new ArrayList<>();
ArrayList<ArrayList<Integer>>result = new ArrayList<>();
result.add(list);
for(int i = 0; i < 5; i++){
list.add(i);
System.out.println("待选结果"+list);
System.out.println("结果集:"+result);
list.remove(list.size()-1);
System.out.println("result变化"+result);
System.out.println("========================");
}
}

于是乎,在历经千辛万苦九九八十一难后,我终于解出了这道题

附上原题链接:寻找二叉树值的和为特定值的路径
简单回溯算法。
错误(×):

正确(√):

?
好了,这次错误就当一次教训了…………
|