简体   繁体   English

传递新的 ArrayList 与传递 ArrayList 作为函数(Java)中的参数

[英]Passing new ArrayList vs Passing ArrayList as a parameter in Function(Java)

Please help me understand the difference.请帮助我理解其中的区别。 Like in first code snippet, I'm passing the updated ArrayList as a parameter in the recursive function in Line 1 & 2. This is giving me wrong answer.就像在第一个代码片段中一样,我在第 1 行和第 2 行的递归 function 中将更新的 ArrayList 作为参数传递。这给了我错误的答案。

public static void rootToLeafPaths(TreeNode node, ArrayList<Integer> sub){
        if(node == null)
            return;
        sub.add(node.val);
        if(node.left == null && node.right == null){
            list.add(sub);
            return;
        }
        rootToLeafPaths(node.left,sub); //LINE 1
        rootToLeafPaths(node.right,sub); //LINE 2
        sub.remove(sub.size()-1);    
    }

In the second code snippet I'm passing a newly created ArrayList(in Line 3 & 4) which is giving me the correct answer.在第二个代码片段中,我传递了一个新创建的 ArrayList(在第 3 行和第 4 行),它给了我正确的答案。

public static void rootToLeafPaths(TreeNode node, ArrayList<Integer> sub){
            if(node == null)
                return;
            sub.add(node.val);
            if(node.left == null && node.right == null){
                list.add(sub);
                return;
            }
            rootToLeafPaths(node.left,new ArrayList<Integer> (sub)); // LINE 3
            rootToLeafPaths(node.right,new ArrayList<Integer> (sub)); // LINE 4
            sub.remove(sub.size()-1);    
    }

Help me understand the difference.帮助我理解其中的区别。

This method is supposed to provide the root to leaf paths of a binary tree.该方法应该提供二叉树的根到叶路径。 Like in first case it is giving me [[1, 2, 4], [1, 2, 4], [1, 2, 4]] as output which is wrong, but when I'm passing a newly created ArrayList each time it is giving me [[1, 2, 4, 6, 8], [1, 2, 5, 7, 9, 10], [1, 3]] as output which is correct就像在第一种情况下,它给我 [[1, 2, 4], [1, 2, 4], [1, 2, 4]] 作为 output 这是错误的,但是当我通过一个新创建的 ArrayList 时它给我 [[1, 2, 4, 6, 8], [1, 2, 5, 7, 9, 10], [1, 3]] 作为 output 的时间是正确的

In list.add(sub) you are adding sub List as an element of list List .list.add(sub)中,您将sub List添加为list List的一个元素。

In your first snippet, sub always references the same List , which means your output list will contain multiple references to the same List .在您的第一个片段中, sub始终引用相同的List ,这意味着您的 output list将包含对同一List的多个引用。 Hence the wrong answer.因此错误的答案。

In your second snippet, you create a copy of sub for each recursive call, which means you are adding different List instances to your list .在您的第二个片段中,您为每个递归调用创建sub的副本,这意味着您将不同的List实例添加到您的list

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM