首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >为什么这里是"res.add(new list(ArrayList<>));“?

为什么这里是"res.add(new list(ArrayList<>));“?
EN

Stack Overflow用户
提问于 2018-08-13 23:22:23
回答 2查看 995关注 0票数 2
代码语言:javascript
运行
复制
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);
    }
}

我正在研究Leetcode 113. Path Sum II。这与问题本身无关。我想知道为什么我必须在第13行编写res.add(new ArrayList<>(list));而不是直接编写res.add(list);

EN

回答 2

Stack Overflow用户

发布于 2018-08-13 23:24:41

编写new ArrayList<>(list)将创建一个新列表,其中包含list中的所有元素。这是必需的,因为在调用list.remove(list.size()-1);的函数结束时,需要修改list变量。

如果要直接在res中添加listremove调用也会修改res

另一个相关的例子:

代码语言:javascript
运行
复制
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.
        }
    }
}
票数 4
EN

Stack Overflow用户

发布于 2018-08-13 23:25:16

new ArrayList<>(list)将创建list的副本,这将确保元素存储到res中。

否则,在list.remove(list.size()-1)之后,res中的元素将被删除。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51825663

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档