java中的深度复制和浅复制的BUG

刷题刷到LeetCode回溯DFS的算法题39题的时候,碰见一个Arraylist里面的bug,其中dfs函数里面的第一个if判断里面的语句

java 复制代码
paths.add(path);
path.clear();

其中path是添加了path,但是添加之后path.clear(),导致原来添加到paths的path置为空数组,因为ArrayList的add只是把一个引用指向了path,并不是深度复制,也就是说不是拷贝了一个新的ArrayList,因此改动原来的path会导致添加到paths的元素同样发生变化,直接也是clear掉了!

java 复制代码
package org.example.SolutionTest3;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        int n=candidates.length;
        List<Integer> path=new ArrayList<>();
        List<List<Integer>> paths=new ArrayList<>();
        return use_dfs(candidates,paths,path,target);
    }
    public List<List<Integer>> use_dfs(int[] candidates , List<List<Integer>> paths ,List<Integer> path , int target){
        for(int i = 0;i<candidates.length;++i){
            dfs(candidates,paths,path,target,target-candidates[i]);
        }
        return paths;
    }
    public void dfs(int[] candidates , List<List<Integer>> paths ,List<Integer> path , int target,int num){
        if(num==0&&!path.isEmpty()){
            System.out.println("path = " + path);
            paths.add(path);
            path.clear();
            //path=new ArrayList<>();
            return;
        }else if(num<0&&!path.isEmpty()){
            path.remove(path.size()-1);
            return;
        }

        for( int i = 0 ; i<candidates.length;++i){
            int next_num = num-candidates[i];
            if(next_num<0){
                continue;
            }
            path.add(candidates[i]);
            dfs(candidates,paths,path,target , next_num);

        }
    }
    public static void main(String[] args) {
        List<List<Integer>> lists = new Solution().combinationSum(new int[]{
                        2, 3, 6, 7
                },
                7);
        System.out.println(lists);
    }
}
相关推荐
艾派森几秒前
基于 Rokid CXR-M SDK 构建 AR 远程专家协作系统:从零实现眼镜端自定义 UI 与实时交互
java
cxyxiaokui00116 分钟前
🔥不止于三级缓存:Spring循环依赖的全面解决方案
java·后端·spring
UCoding21 分钟前
我们来学AI编程 -- vscode开发java
java·vscode·ai编程
一线大码23 分钟前
开发 Java 项目时的命名规范
java·spring boot·后端
neoooo23 分钟前
Apollo兜底口诀
java·后端·架构
程序员小假24 分钟前
什么是线程池?它的工作原理?
java·后端
盖世英雄酱5813631 分钟前
java 深度调试【第一章:堆栈分析】
java·后端
本就一无所有 何惧重新开始1 小时前
Redis技术应用
java·数据库·spring boot·redis·后端·缓存
低音钢琴1 小时前
【SpringBoot从初学者到专家的成长11】Spring Boot中的application.properties与application.yml详解
java·spring boot·后端
蓝色汪洋1 小时前
string字符集
java·开发语言