强制转换不适用于嵌套列表对象类型,并返回空列表(List< List< Integer>>)

强制转换不适用于嵌套列表对象类型,并返回空列表(List< List< Integer>>)

问题描述:

我正在做一些与回溯有关的leetcode挑战,即: https://leetcode.com/problems/permutations/

I'm doing some leetcode challenges related to backtracking, namely: https://leetcode.com/problems/permutations/

我需要返回 List< List< Integer>> 作为类型,但是我的 List< List< List< Integer>> 仅在我正确填充时接受 List< Integer> 作为我的参数,然后将其转换为 ArrayList< Integer> ,同时将其添加到主要结果中.

Where I need to return List<List<Integer>> as the type, however my List<List<Integer>> only gets populated correctly if I accept List<Integer> as my parameter and I cast it to ArrayList<Integer> while I add it in the main result.

代码:

    List<List<Integer>> result = new ArrayList<>();
    public List<List<Integer>> permute(int[] nums) {
        bt(new ArrayList<Integer>(), nums);
        return result;
    }
    
    public void bt(List<Integer> tmp, int[] nums){
        if(tmp.size() == nums.length){
            result.add(new ArrayList<>(tmp));  // HERE
        }else{
          // some logic here
            
        }
    }

输出:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]

Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]

相对,下面的代码中我接受ArrayList作为参数

代码:

List<List<Integer>> result = new ArrayList<>();   
public List<List<Integer>> permute(int[] nums) {
    bt(new ArrayList<Integer>(), nums);
    return result;
}
public void bt(ArrayList<Integer> tmp, int[] nums){
    if(tmp.size() == nums.length){
        result.add(tmp); // HERE
    }else{
      ... some logic here
    
    }
}

输出: [[],[],[],[],[],[]]

Output: [[],[],[],[],[],[]]

您的代码中没有强制转换,并且您的方法是否接受 List< Integer> ArrayList< Integer> .

There is no casting in your code, and it doesn't matter if your method accepts a List<Integer> or an ArrayList<Integer>.

重要的是,在第一个代码段中,您将输入列表 tmp 的副本添加到结果( result.add(new ArrayList<>(tmp))),而在第二个代码段中,您将引用添加到原始的 tmp 列表( result.add(tmp)).

What matters it that in the first snippet you add a copy of the input list tmp to the result (result.add(new ArrayList<>(tmp))) while in the second snippet you add a reference to the original tmp list (result.add(tmp)).

在后一种情况下,如果您以后在 tmp 引用的列表中进行更改,则这些更改将反映在 result 列表的所有元素中,因为它们是所有对同一个列表对象的引用.

In the latter case, if you later make changes in the list referenced by tmp, these changes are reflected in all the elements of the result list, since they are all references to the same list object.