dd("humor");
addBook("Indexed", keywords4);
List keywords5 = new LinkedList();
keywords5.add("marketing"); keywords5.add("business");
keywords5.add("design"); keywords5.add("emotion");
keywords5.add("functionality"); keywords5.add("consumers");
addBook("Emotional Design", keywords5);
keywords.clear();
}
这里没有什么值得关注的地方;现在只需调用 addBooks() 方法。清单 6 给出 BookSearcher 的完整 版本,其中在构造函数中调用 addBooks(),从而自动地填充一些书名和关键字:
清单 6. 完整的 BookSearcher 类
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public class BookSearcher {
private Map books;
public BookSearcher() {
books = new HashMap();
// for example purposes
addBooks();
}
public void setBooks(Map books) {
this.books = books;
}
public void addBook(String title, List keywords) {
books.put(title, keywords);
}
public void addKeyword(String title, String keyword) {
List keywords = (List)books.get(title);
if (keywords != null) {
keywords.add(keyword);
// No need to manually "re-put" the list
} else {
keywords = new LinkedList();
keywords.add(keyword);
books.put(title, keywords);
}
}
public List getKeywords(String title) {
return (List)books.get(title);
}
public List search(String keyword) {
List results = new LinkedList();
for (Iterator i = books.keySet().iterator(); i.hasNext(); ) {
String title = (String)i.next();
List keywords = (List)books.get(title);
if (keywords.contains(keyword)) {
results.add(title);
}
}
return results;
}
private void addBooks() {
List keywords = new LinkedList();
keywords.add("presentation"); keywords.add("Keynote");
keywords.add("PowerPoint"); keywords.add("design");
addBook("Presentation Zen", keywords);
List keywords2 = new LinkedList();
keywords2.add("presentation"); keywords2.add("user interface design");
keywords2.add("pictures"); keywords2.add("visuals");
addBook("The Back of the Napkin", keywords2);
List keywords3 = new LinkedList();
keywords3.add("marketing"); keywords3.add("business");
keywords3.add("commercials"); keywords3.add("consumers");
addBook("Purple Cow", keywords3);
List keywords4 = new LinkedList();
keywords4.add("marketing"); keywords4.add("business");
keywords4.add("notecards"); keywords4.add("design");
keywords4.add(&q
|