上的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
啊,这是递归的美,对吧?您首先为空列表定义基本情况。然后,在每次递归中,您都给该方法一个较小的问题,并假设它返回的解决方案是正确的,然后对解决方案采取行动以获得更大的解决方案。我会尽力解释它。 :) –