ArrayList的深拷贝和浅拷贝问题,arraylist拷贝
分享于 点击 49188 次 点评:150
ArrayList的深拷贝和浅拷贝问题,arraylist拷贝
需求:leetcode的八皇后问题(编号:51)的解决过程中,需要用
List<List<String>> result = new ArrayList<>();来存储结果
对应的我使用
List<List<Integer>> mark = new ArrayList<>();存储标记
List<String> location = new ArrayList<>();存储位置
当向
result.add(location);
或者用
List<List<Integer>> temp_mark = new ArrayList<>(mark);记录标记都会出现数据被修改问题。
原因:ArrayList是一个引用,记录的是指向位置,如果对应位置上的数据被修改,结果就不是想要的了。
引出:深拷贝与浅拷贝
result.add(new ArrayList<>(location));解决了第一个问题,此处只需要浅拷贝即可
List<List<Integer>> temp_mark = new ArrayList<>(mark);解决不了第二个问题,此处需要深拷贝
即:
List<List<Integer>> temp_mark = new ArrayList<>(); for(List<Integer> item : mark) { temp_mark.add(new ArrayList<>(item)); }
相关文章
- 暂无相关文章
用户点评