有兩種乾淨的方法可以使方法將多個返回值傳遞給調用者。
第一種也是最簡單的方法是返回一個包含所有返回值的對象。它可能是一個集合,就像一個List,或者它可能是你自己的價值類的一個對象。
List<Person> matches = findMatches(peopleDB,criteria);
MatchReport report = findMatchesAsReport(peopleDB);
...
public List<Person> findMatches(PersonSource source,Criteria criteria) {
List<Person> list = new ArrayList<Person>();
while(source.hasNext()) {
Person person = source.next();
if(person.matches(criteria)) {
list.add(person);
}
}
return list;
}
第二,更復雜的方法是定義一個處理,你的方法可以用手項目,因爲它遇到他們。
public interface PersonHandler {
public void onPerson(Person p);
}
然後定義你的方法,這樣的處理程序將被傳遞給它:
public void findMatches(PeopleSource source, Criteria criteria, PersonHandler handler) {
while(source.hasNext()) {
Person person = source.next();
if(person.matches(criteria)) {
handler.onPerson(person);
}
}
}
調用者可以再定義一個PersonHandler比滿足自己的需求:
private static class PrintToWriterPersonHandler implements PersonHandler {
private PrintWriter writer;
public WriteToStreamPersonHandler(PrintWriter writer) {
this.writer = writer;
}
public void onPerson(Person p) {
writer.println(person);
}
}
...
findMatches(source,criteria,new PrintToWriterPersonHandler(System.out));
這是退出參與其中,對於初學者來說很複雜。但值得記住。這意味着您可以處理產生大量響應的方法,而無需等到方法結束,並且不會結束內存中的巨大列表。這也意味着你可以處理來自可能無限期運行的方法的輸出!
我相信你必須在調用方法的循環中調用這個方法。其他選項是使用分隔符連接字符串並返回整個字符串。 – Sid