上的Java調用方法所以我正在閱讀Java,並且遇到了一個示例。我不知道它是如何工作的。以下您將在ConsLoRunner
類中看到方法sortByTime()
。我的問題是它如何能夠輸出一些東西,難道它只是一遍又一遍地重複這種方法,並且永遠不會達到insertByTime(this.first)
方法?無法理解方法
邊注意:這個例子是馬拉松跑步者的例子,並根據他們的時間(從最快到最慢)對他們進行排序。
class Runner {
String name;
int age;
int bib;
boolean isMale;
int pos;
int time;
Runner(String name, int age, int bib, boolean isMale, int pos, int time) {
this.name = name;
this.age = age;
this.bib = bib;
this.isMale = isMale;
this.pos = pos;
this.time = time;
}
public boolean finishesBefore(Runner r) {
return this.time < r.time;
}
}
interface ILoRunner {
ILoRunner sortByTime();
ILoRunner insertByTime(Runner r);
}
class MtLoRunner implements ILoRunner {
public ILoRunner sortByTime() {
return this;
}
public ILoRunner insertByTime(Runner r) {
return new ConsLoRunner(r, this);
}
}
class ConsLoRunner implements ILoRunner {
Runner first;
ILoRunner rest;
ConsLoRunner(Runner first, ILoRunner rest) {
this.first = first;
this.rest = rest;
}
/*******HOW DOES IT DO THIS?????**********/
public ILoRunner sortByTime() {
return this.rest.sortByTime().insertByTime(this.first);
}
public ILoRunner insertByTime(Runner r) {
if (this.first.finishesBefore(r)) {
return new ConsLoRunner(this.first, this.rest.insertByTime(r));
}
else {
return new ConsLoRunner(r, this);
}
}
}
class ExamplesRunners {
MtLoRunner empty = new MtLoRunner();
Runner tim = new Runner ("Tim", 1, 2, true, 5, 6);
Runner bob = new Runner ("Bob", 5, 6, true, 9, 50);
Runner jim = new Runner ("Jim", 5, 6, true, 10, 40);
ILoRunner list1 = new ConsLoRunner(this.tim, new ConsLoRunner(this.bob, new ConsLoRunner(this.jim, this.empty)));
boolean testSort(Tester t) {
return t.checkExpect(this.list1.sortByTime(), new ConsLoRunner(this.tim, new ConsLoRunner(this.jim, new ConsLoRunner(this.bob, this.empty))));
}
}
這真是太神奇了,非常感謝你。我仍然困惑的一個部分是Java如何知道'1'。對列表的其餘部分進行排序。你所做的只是在列表的其餘部分調用一個方法?它如何神奇地分揀它? – CtrlAltDelete
啊,這是遞歸的美,對吧?您首先爲空列表定義基本情況。然後,在每次遞歸中,您都給該方法一個較小的問題,並假設它返回的解決方案是正確的,然後對解決方案採取行動以獲得更大的解決方案。我會盡力解釋它。 :) –