62,614
社区成员
发帖
与我相关
我的任务
分享
b1.getISBN().compareTo(b2.getISBN())
,通过ISBN排序。不过我还是有一点不太清楚,为什么在这儿要用到new Comparator<Book>()
? 一般是在什么情况下用到这个的?class Library {
//如果是数据库实体映射,那么自己定义多对一关系
//即多个book对应一个library
Set<Book> set = new TreeSet(new Comparator<Book>() {
public int compare(Book b1, Book b2) {
//自己定义排序方式
}
});
public boolean sortedInsert(Book newbook){
set.add(newbook);
}
public Book searchISBN(String isbn){
for (Book b : set) {
if (b.getIsbn().equals(isbn)) {
return b;
}
}
return null;
}
public Collection searchAuthor(String autor){
Set<Book> tmp = new HashSet<Book>();
for (Book b : set) {
if (b.getAuthor().equals(autor)) {
tmp.add(b);
}
}
return tmp;
}
}
public Map<String, String> stockByAuthor(){
Map<String,String> map = new TreeMap<String,String>();
Iterator<Book> i = set.iterator();
while(i.hasNext()){
Book b = i.next();
map.put(b.getTitle(),b.getAuthor());
}
Set<Map.Entry<String,String>> entries = map.entrySet();
for(Map.Entry<String, String> e:entries)
System.out.println(e);
return map;
}