【发布时间】:2016-10-15 00:32:08
【问题描述】:
我认为当 ArrayList 作为参数传递并在递归期间更新时,ArrayList 在所有递归堆栈帧中都会被修改。这是不正确的吗?
我正在尝试传递一个空的 ArrayList,然后用单词的排列填充它。我知道我不必传递一个空的 ArrayList 作为参数,而是可以从此方法返回一个 ArrayList,但我想知道我对递归期间对象如何存储和更新的理解是否不正确。
public static void findPermutations(String str, ArrayList<String> l, int from, int to, StringBuilder sb){
if(from+1 == to){
l.add(""+str.charAt(from));
return;
}
if(from+2 == to){
l.add(""+str.charAt(from)+str.charAt(from+1));
l.add(""+str.charAt(from+1)+str.charAt(from));
return;
}
char curr = str.charAt(from);
findPermutations(str,l,from+1,to,sb);
ArrayList<String> newList = new ArrayList<String>();
for(String s: l){
for(int i=0; i<=s.length(); i++){
sb.append(s.substring(0,i));
sb.append(curr);
sb.append(s.substring(i));
newList.add(sb.toString());
sb.setLength(0);
}
}
//Making a copy of the arraylist
//Shouldn't it update in the other recursion call stacks as well?
l=new ArrayList<String>();
for(String s:newList){
l.add(s);
}
}
【问题讨论】:
-
为什么要在方法中初始化
l? -
如果我们有“abcd”,在基本情况运行后,ArrayList l 包含“cd”和“dc”。然后我将 b 添加到每个字符串中的每个位置,并通过使其引用新的 Arraylist 然后将新列表中的字符串放入其中来覆盖 l 数组。