【问题标题】:ArrayList parameter doesn't update during recursionArrayList 参数在递归期间不更新
【发布时间】: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 数组。

标签: java recursion arraylist


【解决方案1】:

虽然列表是通过引用传入的,但l只引用引用。当您执行l=new ArrayList&lt;&gt;() 时,您只是在更新l 以指向一个新实例。原始列表不受影响,递归堆栈中更靠后的ls 仍在引用原始列表。

【讨论】:

    【解决方案2】:
    //Making a copy of the arraylist
    //Shouldn't it update in the other recursion call stacks as well?
    
    l.clear(); // Do you really want to do this? 
               // It is analogous to the l = new ArrayList<>(), 
               // but it throws away the previous work.
    l.addAll(newList);
    

    该更改会在整个递归过程中更新包含对 l 的引用的所有变量。

    【讨论】:

      猜你喜欢
      • 2014-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-21
      • 1970-01-01
      • 2021-07-22
      • 2021-09-13
      • 2023-01-10
      相关资源
      最近更新 更多