我一直在尝试一个小代码来学习java中的递归。编写了以下方法来使用递归实现线性搜索。但是,当我使用数组和要搜索的变量调用此方法作为输入时,并且当方法到达返回语句时,它不会退出该方法。相反,执行完 if 循环中的语句后,它再次进入 else 循环。
我有 2 个问题。
1) 为什么在到达“return”时不退出方法?
2)为什么执行完if循环就进入了else循环?
我在这里做错了什么?有人可以看看并帮助我吗。
linearRecursiveSearch(Constants.INPUT_INT_ARRAY, Constants.INPUT_INT_ARRAY[0], Constants.NUMBER_TO_SEARCH);
int count = 0;
public <T> void linearRecursiveSearch(T[] array,T tmp, T value) {
count++;
if (tmp == value) {
System.out.println("The value has been found");
return;
} else {
for (int i = count; i < array.length; i++) {
T tmp1 = array[i];
linearRecursiveSearch(array,tmp1, value);
}
}
}
最佳答案
1) Why is it not exiting the method on reaching 'return' ?
它正在退出调用return
的方法。
2) Why is it entering the else loop after executing the if loop ?
调用 return
的方法没有调用 else 循环。然而,该方法还有其他调用,它们会排队等候在调用 return
的方法完成后恢复。
混淆的地方在于方法的调用不止一次,而且并不是都在调用return。
也许这有助于记忆方法调用发生时发生的情况,即当前方法的状态被压入堆栈。然后在堆栈上为新调用保留空间,然后调用该方法。一旦该方法完成,它的状态就会从堆栈中弹出。它的返回值可用,并且现在位于堆栈顶部的先前方法被恢复。
在递归过程中,同一个方法可能会被压入堆栈数百次。这意味着该方法可以被调用数百次,然后随着堆栈展开,每个方法将被恢复数百次。因此,仅仅因为当前正在调用的方法调用返回(并退出)并不意味着所有其他排队的实例也会返回(和退出)。事实上,它实际上意味着前一个方法(调用此方法的方法)将恢复。
考虑以下版本,注意它不包含 for 循环或任何全局状态:
public <T> int linearRecursiveSearch(T[] array, T targetValue) {
return linearRecursiveSearch( array, targetValue, 0 );
}
private <T> int linearRecursiveSearch(T[] array, T targetValue, int i) {
if ( i >= array.length ) {
return -1;
} else if (array[i] == targetValue) {
// == or .equals, or Comparator? task for the reader
return i;
} else {
return linearRecursiveSearch(array, targetValue,i+1);
}
}
关于java - 返回语句在 Java 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33149636/