casting does not work on nested list object type and returns empty lists (List<List<Integer>>)

[亡魂溺海] 提交于 2021-01-05 07:01:26

问题


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

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.

Code:

    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
            
        }
    }

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

Versus, the code below where i accept ArrayList as the parameter

Code:

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


回答1:


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

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)).

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.



来源:https://stackoverflow.com/questions/64221648/casting-does-not-work-on-nested-list-object-type-and-returns-empty-lists-listl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!