为什么我可以将比较器对象传递给排序方法?

Why can i pass a comparator object to the sort method?

从我见过的所有排序方法示例中,我从未遇到过其中传递比较器定义的示例。 如果比较器设计为return一个负数、正数或0来对对象进行排序,那么sort方法如何处理这些信息? sort方法如何从Comparator定义中获取有意义的信息并执行其操作?

这里是有问题的排序方法:

    public void sort() {
        library.sort(new BookComparator());
    }

这是整个比较器class:

import java.util.Comparator;

public class BookComparator implements Comparator<Book> {
    public int compare(Book a, Book b) {
        if(a == null || b == null) {
            throw new NullPointerException();
        }

        int result = 0 ;

        if(a.getAuthor() == null) {
            if(b.getAuthor() != null) {
                result = -1;
            }
        } else if(b.getAuthor() == null) {
            result = 1;
        } else {
            result = a.getAuthor().compareTo(b.getAuthor());
        }
        if(result !=0) {
            return result;
        }

        if(a.getTitle() == null) {
            if(b.getTitle() != null) {
                result = -1;
            }
        } else if(b.getTitle() == null) {
            result = 1;
        } else {
            result = a.getTitle().compareTo(b.getTitle());
        }

        if(result !=0) {
            return result;
        }

        if(a.getYear() < b.getYear()){
            return -1;
        } else if (a.getYear() == b.getYear()){
            return 0;
        } else {
            return 1;
        }
    }
}

您可以将 Comparator 的实例传递给排序方法,这样您就可以在 default/natural 以外的不同方面进行排序 object。

例如,如果有一本书 object,自然排序可能基于书名。但是,如果您想根据杜威十进制数进行排序怎么办?还是根据作者的名字?还是页数?您可以通过编写一个 Comparator 来比较 Book object.

的那些字段来做到这一点

实际的排序算法不需要知道正在排序的 object。它只需要一个一致的比较器(即比较 A < B 和 B < C,然后比较 A < C 和 C > B 和 B > A,等等)

If the comparator is designed to return a negative, positive or 0 to sort the objects, what does the sort method do with this information? How does the sort method obtain meaningful information from the Comparator definition and perform its operation?

基于比较器的排序方法(例如合并排序或冒泡排序)需要反复查看集合中的两个元素并决定应该去哪一个 "first"。该决定由比较器做出,returns "smaller"、"larger" 或 "same size".

这些信息就足够了,排序方法不需要了解正在排序的对象类型。它可以重新安排集合中元素的顺序,直到 "left" 的所有元素都比 "right" 的元素 "smaller"。

这种方法不适用于 "bucket sort" 之类的东西,它需要为每个元素本身分配绝对数值(而不仅仅是与另一个元素相比的相对值)。