Given the code fragments:

public class Book implements Comparator<Book> {

    String name;
    double price;

    public Book() {
    }

    public Book(String name, double price) {
        this.name = name;
        this.price = price;
    }

    public int compare(Book b1, Book b2) {
        return b1.name.compareTo(b2.name);
    }

    public String toString() {
        return name + ":" + price;
    }
}

and

List<Book> books = Arrays.asList(new Book("Beginning with Java", 2), new Book("A Guide to Java Tour", 3));
Collections.sort(books, new Book());
System.out.print(books);

What is the result?

A.

[A Guide to Java Tour:3.0, Beginning with Java:2.0]

B.

[Beginning with Java:2.0, A Guide to Java Tour:3.0]

C. A compilation error occurs because the Book class does not override the abstract method compareTo().
D. An Exception is thrown at run time.

题解

Book 类别实作了 Comparator 界面,并使用 Book 对象的 name 字段的字符串辞典顺序来作为排序的依据。

程序第 36 行,使用了 Collections 类别的 sort 方法并传入 Book 这个 Comparator 对象来排序集合对象。

由于 A 的辞典顺序在 B 的前面,因此排序之后会输出:

[A Guide to Java Tour:3.0, Beginning with Java:2.0]