为了排序,我们可以实现Collections.sort() 或者Arrays.sort() 方法,需要两个参数,分别是需要排序的对象数组以及自己实现Comparator 接口 。如下例子:
/* Here we have a class called books, we want to sort the array of books objects according to its attributes*/
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
}
});
比较简便的一种办法是自己写一个Comparator匿名类如上例所示