《易错点》ArrayList作为函数参数传参

场景:

今天在做力扣39. 组合总和的时候,调试半天不得其解,室友一语中的。

题目如下:

    public static List<List<Integer>> res = new ArrayList<>();

    public static List<List<Integer>> combinationSum(int[] candidates, int target) {
        Arrays.sort(candidates);
        trackBack(candidates,target,new ArrayList<Integer>(),0);
        return res;
    }
    
    public static void trackBack(int[] candidates, int target, ArrayList<Integer> integers, int i) {
        if(target < 0) return;
        if(target == 0){
            res.add(new ArrayList<>(integers));
            /**
            res.add(integers);
             **/
            return;
        }
        for (int start = i; start < candidates.length; start++) {
            integers.add(candidates[start]);
            trackBack(candidates,target - candidates[start],integers,start);
            integers.remove(new Integer(candidates[start]));
        }
    }
代码块为:res.add(integers);
结果为:[[], []]

代码块为:res.add(new ArrayList<>(integers));
结果为:[[2, 2, 3], [7]]

总结:

  • ArrayList integers作为参数传递时,传递的是此对象所在的地址;
  • 我在回溯修改integers时,修改的都是所在此地址中的实际数据值;
  • 所以如果是第一种:最后结果全是空,因为运行结束,integers中都被删完了;
  • 第二种是每次add时,都重新创建对象,这样才能保存有效值。
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值