Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why "res.add(new ArrayList<>(list));" here?

Tags:

java

class Solution {
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        List<List<Integer>> res = new ArrayList<>();
        if(root == null) return res;
        List<Integer> list = new ArrayList<>();
        helper(res, list, root, sum);
        return res;
    }
    public void helper(List<List<Integer>> res, List<Integer> list, TreeNode root, int sum){
        list.add(root.val);
        if(root.left == null && root.right == null){
            if(root.val == sum)
                res.add(new ArrayList<>(list));
        }
        if(root.left != null)
            helper(res, list, root.left, sum-root.val);
        if(root.right != null)
            helper(res, list, root.right, sum-root.val);
        list.remove(list.size()-1);
    }
}

I am working on Leetcode 113. Path Sum II. It's not about the problem itself. I want to know why I have to write res.add(new ArrayList<>(list)); instead of writing res.add(list); directly in line 13.

like image 860
Morty Avatar asked Jul 23 '26 00:07

Morty


1 Answers

Writing new ArrayList<>(list) creates a new list, containing all the elements in list. This is required, since at the end of the function you are calling list.remove(list.size()-1);, you are thus modifying the list variable.

If you were to add list directly in res, the remove call would also modify res.

Another relevant example:

class MyClass {
    public int modify = 5;
}

class Test {
    public static void myFunction() {
        MyClass object = new MyClass();
        System.out.println(object.modify); // prints 5.

        ArrayList<MyClass> myList = new ArrayList<>();
        myList.add(object);

        object.modify = 800;
        for(MyClass item : myList) {
            System.out.println(item.modify); // prints 800.
        }
    }
}
like image 139
Pieter De Clercq Avatar answered Jul 25 '26 13:07

Pieter De Clercq



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!