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);
    }
}
相关推荐
hong_zc1 小时前
算法【Java】—— 二叉树的深搜
java·算法
进击的女IT2 小时前
SpringBoot上传图片实现本地存储以及实现直接上传阿里云OSS
java·spring boot·后端
Miqiuha2 小时前
lock_guard和unique_lock学习总结
java·数据库·学习
一 乐3 小时前
学籍管理平台|在线学籍管理平台系统|基于Springboot+VUE的在线学籍管理平台系统设计与实现(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端·学习
数云界3 小时前
如何在 DAX 中计算多个周期的移动平均线
java·服务器·前端
阑梦清川3 小时前
Java继承、final/protected说明、super/this辨析
java·开发语言
快乐就好ya5 小时前
Java多线程
java·开发语言
IT学长编程5 小时前
计算机毕业设计 二手图书交易系统的设计与实现 Java实战项目 附源码+文档+视频讲解
java·spring boot·毕业设计·课程设计·毕业论文·计算机毕业设计选题·二手图书交易系统
CS_GaoMing5 小时前
Centos7 JDK 多版本管理与 Maven 构建问题和注意!
java·开发语言·maven·centos7·java多版本
艾伦~耶格尔6 小时前
Spring Boot 三层架构开发模式入门
java·spring boot·后端·架构·三层架构