private int bkicalc(int i, List<Integer> history) {
List<Integer> subList = history.subList(history.size()-1 - i, history.size()-1);
Set<Integer> uniliste = new HashSet<Integer>(subList);
if (uniliste.size() == 4) {
if (i>5) {
System.out.println(i);
}
return i;
} else {
this.bkicalc(i 1, history);
}
System.out.println("else was skipped");
return 404;
}
嗨,這個方法從 for 回圈中被訪問了 1000 次,并且在 1/10 次中它會跳過 else 并回傳 404。我無法向自己解釋為什么會發生這種情況。
希望你能幫助我。
uj5u.com熱心網友回復:
你從if分支回傳,但不是從else分支回傳。因此,診斷和 404 回傳并不表示else已跳過,而是表示已采取。分支遞回是無關緊要的:除非從遞回呼叫中拋出例外,否則該else呼叫最終將回傳,此時控制只是傳遞出else塊。
看起來您可能希望在else分支中回傳遞回呼叫的結果:
private int bkicalc(int i, List<Integer> history) {
List<Integer> subList = history.subList(history.size()-1 - i, history.size()-1);
Set<Integer> uniliste = new HashSet<Integer>(subList);
if (uniliste.size() == 4) {
if (i>5) {
System.out.println(i);
}
return i;
} else {
return this.bkicalc(i 1, history); // <-- here
}
assert false : "unreachable";
return 404;
}
您甚至可能會發現編譯器實際上將 標記return 404為不可訪問。
另請注意,您的子串列上的界限有點??令人驚訝。提供 to 的上限List.subList()是排他性的,而不是包含性的,因此您始終忽略考慮的最后一個元素history。如果這是故意的,那么添加這樣的代碼注釋將是明智的。
此外,如果history實際上總體上不包含至少 4 個不同的元素,那么在一些遞回之后,此方法將失敗并回傳IndexOutOfBoundsException. 如果它最初總共不包含至少 5 個元素(記住一個被忽略),這當然肯定會發生。
最后,遞回似乎是浪費和不必要的混亂。出于各種原因,迭代方法會更好。(幾乎總是如此。)示例:
private int bkicalc(int i, List<Integer> history) {
if (history.size() >= 5) {
Set<Integer> uniliste = new HashSet<Integer>(
history.subList(history.size() - 5, history.size() - 1));
ListIterator<Integer> iterator = history.listIterator(history.size() - 5);
while (uniliste.size() < 4 && iterator.hasPrevious()) {
uniliste.add(iterator.previous());
}
if (uniliste.size() == 4) {
int i = history.size() - 1 - iterator.nextIndex();
if (i > 5) {
System.out.println(i);
}
return i;
}
}
// Fewer than 4 distinct elements (ignoring the last)
return -1;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/466904.html
下一篇:如何在r的回圈內使用if條件
