我有一个关于将一个字符串数组列表添加到另一个数组列表中的问题,代码如下:
public List<List<Integer>> combinationSum(int[] candidates,int target){
List<List<Integer>> res=new ArrayList<>();
Arrays.sort(candidates);
List<Integer>tempList=new ArrayList<>();
backtrack(res,tempList,candidates,target,0);
return res;
}
public void backtrack(List<List<Integer>>res, List<Integer>tempList,
int[]nums, int remain, int start){
if(remain==0) res.add(new ArrayList<>(tempList));
if(remain<0) return;
for(int i=start;i<nums.length;i++){
tempList.add(nums[i]);
backtrack(res,tempList,nums,remain-nums[i],i);
tempList.remove(tempList.size()-1);
}
}
我想知道“回溯”功能中为什么要将tempList添加到res
new Arraylist(tempList)
中时为什么需要使用Arraylist
。为什么我们不能将tempList像if(remain==0) res.add(tempList)
那样放入res,因为我认为tempList之前已经声明为arraylist
并作为一个参数传递了。谢谢。 最佳答案
这行res.add(new ArrayList<>(tempList));
的作用是创建一个新的ArrayList,其内容与tempList相同。这使您可以在tempList上添加/删除元素,而不会影响添加到res
中的浅表副本
public static void main( String[] args ) {
List<String> listA = new ArrayList<>();
listA.add( "listA" );
listA.add( "listAA" );
List<String> listB = new ArrayList<>();
listB.add( "listB" );
listB.add( "listBB" );
// add both our lists above to a new list of lists
List<List<String>> manyLists = new ArrayList<>();
manyLists.add( listA );
manyLists.add( new ArrayList<>( listB ) );
// clear the contents of both list A and list B
listA.clear();
listB.clear();
// both of these will be empty because we simply added the reference for listA when we did `manyLists.add( listA );`
System.out.println( "listA contents -> " + listA );
System.out.println( "listA contents in many lists -> " + manyLists.get( 0 ) );
System.out.println();
// listB will be empty, but manyLists.get( 1 ) will not, because we created a copy of listB (a new Object) before adding it to our manyLists
// So any changes to listB won't affect our new ArrayList in manyLists.get( 1 )
// NOTE: This does not make a copy of the contents (Objects) in listB (this is only a shallow copy)
// those still point to the original references (in this case Strings)
System.out.println( "listB contents -> " + listB );
System.out.println( "listB contents in many lists -> " + manyLists.get( 1 ) );
}
// Output:
// listA contents -> []
// listA contents in many lists -> []
// listB contents -> []
// listB contents in many lists -> [listB, listBB]
关于java - 如何在Java中将Arraylist添加到另一个Arraylist中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58015314/