为什么将ArrayList分配给新的ArrayList临时

为什么将ArrayList分配给新的ArrayList临时

本文介绍了为什么将ArrayList分配给新的ArrayList临时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在看leetcode上置换问题的代码.例如,[1,2,3]具有以下排列:[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2]和[3,2,1].我发现有一句话

I am looking at the code for Permutations problem on leetcode. For example,[1,2,3] have the following permutations:[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1].And I found there is one sentence

ArrayList<Integer> temp = new ArrayList<Integer>(l);

我不知道为什么这里需要将"l"分配给"temp".而且我尝试使用current.add(l)direclty,但给了我错误的答案.你能帮我吗?

I have no idea why here needs to assign the "l" to "temp". And I tried current.add(l) direclty but gave me the wrong answer. Can you help me with this?

public class Solution {

    public ArrayList<ArrayList<Integer>> permute(int[] num) {
        ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();

        //start from an empty list
        result.add(new ArrayList<Integer>());

        for (int i = 0; i < num.length; i++) {
            //list of list in current iteration of the array num
            ArrayList<ArrayList<Integer>> current = new ArrayList<ArrayList<Integer>>();

            for (ArrayList<Integer> l : result) {
                // # of locations to insert is largest index + 1
                for (int j = 0; j < l.size()+1; j++) {
                    // + add num[i] to different locations
                    l.add(j, num[i]);
                    ArrayList<Integer> temp = new ArrayList<Integer>(l);

                    current.add(temp);

                    //System.out.println(temp);

                    // - remove num[i] add
                    l.remove(j);
                }
            }

            result = new ArrayList<ArrayList<Integer>>(current);
        }

        return result;
    }
}

推荐答案

他不是-那将是:

ArrayList<Integer> temp = l;

相反,代码在新的ArrayList中创建了l所引用列表内容的副本.这意味着将来对l所引用列表的更改(例如紧随其后对l.remove(j)的调用)不会影响新列表.

Instead, the code creates a copy of the content of the list l refers to, in a new ArrayList. That means that future changes to the list that l refers to (such as the call to l.remove(j) immediately afterwards) don't affect the new list.

作为一个简单的独立示例,请考虑:

As a simple stand-alone example of that, consider:

List<String> original = new ArrayList<>();
original.add("foo");
List<String> copy = new ArrayList<>(original);
System.out.println(copy.size()); // 1
original.add("bar");
System.out.println(copy.size()); // Still 1

诚然,代码是以非常奇怪的方式编写的-直到最终语句result仅包含一个元素,因此对其进行迭代是毫无意义的-但我相信这可以解释您所要求的单个语句.

Admittedly the code is written in a very odd manner - until the final statement, result only ever has a single element, so iterating over it is pretty pointless - but I believe that explains the single statement you were asking about.

这篇关于为什么将ArrayList分配给新的ArrayList临时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 10:35