问题
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