2014年3月21日星期五

经常碰到的bug

Java里 ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();

ArrayList<Integer>> solution = new ArrayList<Integer>>();

result.add(solution); 小心这里,solution是原版object, 如果后面被改动了,result也就跟着变了。

这里和C++里常用的Vector<Vector<int>> result的情况不一样,因为c++里 vector::push_back()是Value to be copied (or moved) to the new element. 复制了,不是原版!

res.push_back(solution);

所以Java里碰到类似情况,最好新建一个拷贝,然后加入result.

没有评论:

发表评论