强制转换不适用于嵌套列表对象类型并返回空列表 (List<List<Integer>>) [英] casting does not work on nested list object type and returns empty lists (List&lt;List&lt;Integer&gt;&gt;)

查看:37
本文介绍了强制转换不适用于嵌套列表对象类型并返回空列表 (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> 只有在我接受 List 作为我的参数,然后将其转换为 ArrayList,同时将其添加到主要结果中.

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: [[],[],[],[],[],[]]

推荐答案

在您的代码中没有强制转换,并且您的方法是否接受 ListArrayList.

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.

这篇关于强制转换不适用于嵌套列表对象类型并返回空列表 (List<List<Integer>>)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆