Java 初学者递归列表



我正在尝试递归打印列表的元素,但是我收到堆栈溢出错误,我不确定为什么,因为这行确保它终止

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; 
}

我不知道为什么会收到错误,也不知道如何从结构上修复它。

您有两个问题,一个您目前还没有解决。

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; 
}

在行中

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

您正在递增索引,因此下一个递归调用将收到相同的索引值而不是递增的值,因此会出现堆栈溢出错误。

要么在调用递归方法之前放置index++,要么像retBetween(++index, lowerValue, upperValue)一样进行预递增