java初学者递归列表

时间:2017-03-16 09:31:47

标签: java recursion

我尝试以递归方式打印列表中的元素,但我收到了堆栈溢出错误,我不确定原因,因为此行确保终止

 if (index < elements.size()){ 

这是元素的实例化

public class RecursiveMethodsList<T extends Comparable<T>> { 

private ArrayList<T> elements= new ArrayList<>(); 

基本上我正在做的是通过一个列表,如果我遇到的值大于或等于我的lowerval参数并且小于或等于我的upperval参数,我将它添加到一个新的列表中完成后返回新列表

这是我的代码

 private RecursiveMethodsList<E> returnBetween(int index, T lowerValue, T upperValue){ 

  RecursiveMethodsList<T> list = new RecursiveMethodsList<T>(); 

  if (index < elements.size()){ //line that prevents overflow 

     if (elements.get(index).compareTo(lowerValue) >= 0 &&
           (elements.get(index).compareTo(upperValue)) <= 0){

        list.add(elements.get(index)); }

     else retBetween(index++, lowerValue, upperValue); 

  }
  return list; 
}

我不知道为什么我收到错误,而且我不知道如何在结构上修复它。

2 个答案:

答案 0 :(得分:1)

你有两个问题,一个你现在还没到达。

private RecursiveMethodsList<E> returnBetween(int index, T lowerValue, T upperValue){ 

   RecursiveMethodsList<T> list = new RecursiveMethodsList<T>(); 

   if (index < elements.size()){ //line that prevents overflow 

      if (elements.get(index).compareTo(lowerValue) >= 0 &&
         (elements.get(index).compareTo(upperValue)) <= 0){

         list.add(elements.get(index));
      }
      // Heres your mistake
      // You essentially pass index all the time, as index++ 
      // Will simply pass index instead of what you think index +1 , and increment index afterwards.
      // You probably also want to add the content of the List generated in
      // the recursive call to the original List you´re using here
      else list.addAll(retBetween(++index, lowerValue, upperValue)); 

   }
   return list; 
}

答案 1 :(得分:0)

在第

else retBetween(index++, lowerValue, upperValue); 

你后续递增索引,因为下一个递归调用接收相同的索引值而不是递增值,因此堆栈溢出错误。

在调用递归方法之前放置index++或者像retBetween(++index, lowerValue, upperValue)那样预先增加