1Z0-809 practice question 15 of 25

Given the code fragments: public class Book implements Comparator { String name; double price; public Book () {} public Book(String name, double…

Full set: 196 questions
Given the code fragments: public class Book implements Comparator { 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 Listbooks = 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?
Answer options
A: [A Guide to Java Tour:3.0, Beginning with Java:2.0] Correct answer
B: [Beginning with Java:2, A Guide to Java Tour:3]
C: A compilation error occurs because the Book class does not override the abstract method compareTo().
D: An Exception is thrown at run time.
Correct Answer:
A. [A Guide to Java Tour:3.0, Beginning with Java:2.0]
Explanation

Collections.sort(List, Comparator) orders the list according to the supplied Comparator instance. new Book() is a Comparator whose compare method orders by the lexicographic value of name. Initial list order: “Beginning with Java”, “A Guide to Java Tour”. After sorting, “A Guide to Java Tour” precedes “Beginning with Java”. toString returns name + “:” + price; a double literal prints with “.0”. Result: [A Guide to Java Tour:3.0, Beginning with Java:2.0].

Why Incorrect

B. Shows the original (unsorted) order—contradicts comparator result.
C. Comparable is unnecessary; Collections.sort(List, Comparator) needs only a Comparator.
D. No exception is thrown; code compiles and runs normally.

References

1. Oracle Java SE 8 API, java.util.Collections, method sort(List, Comparator) — “sorts the specified list according to the order induced by the specified comparator.”

https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#sort-java.util.List-java.util.Comparator-

2. Oracle Java SE 8 API, java.util.Comparator, method compare(T, T).

https://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html#compare-T-T-

3. Java Language Specification §15.21.2, String comparison rules (lexicographic ordering).

https://docs.oracle.com/javase/specs/jls/8/html/jls-15.html#jls-15.21.2

Scroll to Top