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);
    }
}
相关推荐
岁忧17 分钟前
(LeetCode 每日一题) 1865. 找出和为指定值的下标对 (哈希表)
java·c++·算法·leetcode·go·散列表
YuTaoShao20 分钟前
【LeetCode 热题 100】240. 搜索二维矩阵 II——排除法
java·算法·leetcode
考虑考虑1 小时前
JDK9中的dropWhile
java·后端·java ee
想躺平的咸鱼干1 小时前
Volatile解决指令重排和单例模式
java·开发语言·单例模式·线程·并发编程
hqxstudying2 小时前
java依赖注入方法
java·spring·log4j·ioc·依赖
·云扬·2 小时前
【Java源码阅读系列37】深度解读Java BufferedReader 源码
java·开发语言
Bug退退退1233 小时前
RabbitMQ 高级特性之重试机制
java·分布式·spring·rabbitmq
小皮侠3 小时前
nginx的使用
java·运维·服务器·前端·git·nginx·github
Zz_waiting.3 小时前
Javaweb - 10.4 ServletConfig 和 ServletContext
java·开发语言·前端·servlet·servletconfig·servletcontext·域对象
全栈凯哥3 小时前
02.SpringBoot常用Utils工具类详解
java·spring boot·后端