nerdexam
Oracle

1Z0-809 · Question #118

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 =…

The correct answer is A. [A Guide to Java Tour:3, Beginning with Java:2]. Option A is correct because Book implements Comparator<Book> and properly overrides its required compare(Book b1, Book b2) method, which sorts books alphabetically by name. When Collections.sort(books, new Book()) runs, "A Guide to Java Tour" sorts before "Beginning with Java"…

Question

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?

Options

  • A[A Guide to Java Tour:3, Beginning with Java:2]
  • B[Beginning with Java:2, A Guide to Java Tour:3]
  • CA compilation error occurs because the Book class does not override the abstract method compareTo().
  • DAn Exception is thrown at run time.

How the community answered

(63 responses)
  • A
    71% (45)
  • B
    3% (2)
  • C
    8% (5)
  • D
    17% (11)

Explanation

Option A is correct because Book implements Comparator<Book> and properly overrides its required compare(Book b1, Book b2) method, which sorts books alphabetically by name. When Collections.sort(books, new Book()) runs, "A Guide to Java Tour" sorts before "Beginning with Java" (since 'A' < 'B'), producing [A Guide to Java Tour:3, Beginning with Java:2].

Option B is wrong because it reflects the original insertion order - the sort does execute, and alphabetically "A Guide..." precedes "Beginning...".

Option C is wrong because it confuses Comparator with Comparable. Comparator<T> requires compare(T o1, T o2) - which is implemented - not compareTo(). compareTo() belongs to the Comparable interface.

Option D is wrong because the code compiles and runs without error; new Book() is a valid Comparator<Book> instance thanks to the no-arg constructor and the implemented compare method.

Memory tip: Count the parameters - Compar**a**tor takes 2 args (compare(o1, o2)), Compar**able** takes 1 arg (compareTo(o)). If the class implements Comparator and has compare() defined, it compiles and sorts correctly.

Community Discussion

No community discussion yet for this question.

Full 1Z0-809 Practice