我有一个类 Library,它包含 Book 对象数组,我需要根据 Book 的属性(Title 或 PageNumber)对数组进行排序。问题是我不允许将 Comparable 类与 Book 一起使用。你会如何推荐我对图书馆中的书籍数组进行排序?写我自己的排序?或者有没有更简单的方法?如果您需要代码片段,请询问!
问问题
51892 次
4 回答
27
您可以提供一个Comparator
用于比较您希望的任何类型,Comparable
或者以其他方式。
对于您使用的数组和集合
Arrays.sort(array, myComparator);
Collections.sort(list, myComparator);
甚至像 TreeSet 这样的排序集合也可以使用自定义 Comparator
例如
Collections.sort(books, new Comparator<Book>() {
public int compare(Book b1, Book b2) {
return if b1 is greater return +1, if b2 is smaller return -1 otherwise 0
}
});
于 2012-09-16T19:04:28.470 回答
8
如果您可以使用Comparators
,请为您需要的每种排序类型编写一个,例如,升序表示书名,降序表示页码。如果第一个参数大于第二个参数,则a的compare
方法必须返回正数,如果第一个参数小于第二个参数,则返回负数,如果它们相等,则返回零。Comparator
import java.util.Comparator;
import java.util.List;
import java.util.Arrays;
class Book{
String title;
int pageNumber;
public Book(String title, int pageNumber){
this.title = title;
this.pageNumber = pageNumber;
}
String getTitle(){ return title; }
int getPageNumber(){ return pageNumber; }
public String toString(){
return "(" + title + ", " + pageNumber + " pages)";
}
}
public class Library{
// These variables are static because you don't need multiple copies
// for sorting, as they have no intrinsic state.
static private Comparator<Book> ascTitle;
static private Comparator<Book> descPageNumber;
// We initialize static variables inside a static block.
static {
ascTitle = new Comparator<Book>(){
@Override
public int compare(Book b1, Book b2){
return b1.getTitle().compareTo(b2.getTitle());
}
};
descPageNumber = new Comparator<Book>(){
@Override
public int compare(Book b1, Book b2){
// Java 7 has an Integer#compare function
return Integer.compare(b1.getPageNumber(), b2.getPageNumber());
// For Java < 7, use
// Integer.valueOf(n1).compareTo(n2);
// DO NOT subtract numbers to make a comparison such as n2 - n1.
// This can cause a negative overflow if the difference is larger
// than Integer.MAX_VALUE (e.g., n1 = 2^31 and n2 = -2^31)
}
};
}
private Book[] books;
public Book[] getBooks(){ return books; }
public void sortAscTitle(){
Arrays.sort(books, ascTitle);
}
public void sortDescPageNumber(){
Arrays.sort(books, descPageNumber);
}
public Library(Book[] books){
this.books = books;
}
public static void main(String[] args){
Library library = new Library( new Book[]{
new Book("1984", 123),
new Book("I, Robot", 152),
new Book("Harry Potter and the Philosopher's Stone", 267),
new Book("Harry Potter and the Goblet of Fire", 759),
new Book("The Bible", 1623)
});
library.sortAscTitle();
System.out.println(Arrays.toString(library.getBooks()));
library.sortDescPageNumber();
System.out.println(Arrays.toString(library.getBooks()));
}
}
于 2012-09-16T19:47:17.157 回答
1
将其粘贴到您的库中:
java.util.Collections.sort(bookList, bookComparator);
于 2012-09-16T19:07:42.603 回答
0
扩展@PeterLawrey 对 Java 8 的回答,您现在可以使用Lambda 表达式而不是Comparable<T>
委托:
Collections.sort(books, (firstBook, secondBook -> b1 is greater return +1,
if b2 is smaller return -1 otherwise 0));
于 2015-12-05T13:08:09.327 回答