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

go评论63阅读模式

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

# 问题

``````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){
}else{
// 这里有一些逻辑

}
}
``````

[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]

``````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){
}else{
... 这里有一些逻辑

}
}
``````

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

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

Code:

``````    List&lt;List&lt;Integer&gt;&gt; result = new ArrayList&lt;&gt;();
public List&lt;List&lt;Integer&gt;&gt; permute(int[] nums) {
bt(new ArrayList&lt;Integer&gt;(), nums);
return result;
}

public void bt(List&lt;Integer&gt; tmp, int[] nums){
if(tmp.size() == nums.length){
}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&lt;List&lt;Integer&gt;&gt; result = new ArrayList&lt;&gt;();
public List&lt;List&lt;Integer&gt;&gt; permute(int[] nums) {
bt(new ArrayList&lt;Integer&gt;(), nums);
return result;
}
public void bt(ArrayList&lt;Integer&gt; tmp, int[] nums){
if(tmp.size() == nums.length){
}else{
... some logic here

}
}
``````

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

# 答案1

There is no casting in your code, and it doesn't matter if your method accepts a `List&lt;Integer&gt;` or an `ArrayList&lt;Integer&gt;`.

What matters it that in the first snippet you add a copy of the input list `tmp` to the result (`result.add(new ArrayList&lt;&gt;(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.

• 本文由 发表于 2020年10月6日 15:59:55
• 转载请务必保留本文链接：https://go.coder-hub.com/64221648.html
• arraylist
• casting
• java
• list

go 56

go 70

go 84

go 63