Java Comparator Example: Understanding Sorting using Comparator Interface

Java Comparator Example: Sorting a List of Books using Comparator Interface

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?

Answers

Explanations

Click on the arrows to vote for the correct answer

A. B. C. D.

D.

If asList is changed to List, the output would be B, Beginning with java:2.0, A guide to Java Tour:3.0.

The code given defines a class Book that implements the Comparator<Book> interface. The Comparator interface is used to compare objects of a class and to provide a total ordering for a collection of objects. The compare() method defined in the Comparator interface takes two objects of the same type and returns an integer that indicates the order of the objects.

In the given code, the Book class provides an implementation of the compare() method that compares two Book objects based on their names. The toString() method is also overridden to provide a string representation of a Book object.

The code then creates a List<Book> object named books using the Arrays.asList() method. Two Book objects are added to the list using the Book class's two-argument constructor.

The Collections.sort() method is called with the books list and a new instance of the Book class as arguments. The Book instance is used as the Comparator object to sort the books list.

Finally, the sorted books list is printed using the System.out.print() method.

The expected output of the code is:

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

This is because the Book objects in the books list are sorted in ascending order based on their names.

Therefore, the correct answer is B. [Beginning with Java:2.0, A Guide to Java Tour:3.0].