Three books in a list
This program stores three Book objects in a list. Each book has a title, an author and pages. We want the list sorted.
This program stores three Book objects in a list.
Each book has a title, an author and pages. We want the list sorted.
This program stores three Book objects in a list. Each book has a title, an author and pages. We want the list sorted.
Collections.sort(books) asks to sort. Java rejects it.
By title, by author, by pages? Java cannot guess: Book is not Comparable.
Collections.sort(books) asks to sort. Java rejects it. By title, by author, by pages? Java cannot guess: Book is not Comparable.
Book implements Comparable and defines its natural order.
compareTo compares this book with another one. Here, by title.
It returns an integer. Negative: goes before. Zero: equivalent. Positive: goes after.
Book implements Comparable and defines its natural order. compareTo compares this book with another one. Here, by title. It returns an integer. Negative: goes before. Zero: equivalent. Positive: goes after.
Now the sort does run. It takes a pair and asks which one goes first.
The comparison travels to compareTo: "1984" against "Hopscotch".
The answer is negative: "1984" goes first. The pair swaps places.
Now the sort does run. It takes a pair and asks which one goes first. The comparison travels to compareTo: "1984" against "Hopscotch". The answer is negative: "1984" goes first. The pair swaps places.
Only the sign matters. "Fictions" against "Hopscotch": negative, they swap.
"Fictions" against "1984": positive. It is already after: it does not move.
With those answers, the list is now sorted by title.
Only the sign matters. "Fictions" against "Hopscotch": negative, they swap. "Fictions" against "1984": positive. It is already after: it does not move. With those answers, the list is now sorted by title.
And to sort by pages? Comparable allows only one natural order.
A Comparator is an order outside the class: Book is not touched.
And to sort by pages? Comparable allows only one natural order. A Comparator is an order outside the class: Book is not touched.
The sort asks the same questions; now the Comparator answers.
174 pages against 328: negative, the pair swaps places.
736 against 328: positive, it stays. The list is now sorted by pages.
The sort asks the same questions; now the Comparator answers. 174 pages against 328: negative, the pair swaps places. 736 against 328: positive, it stays. The list is now sorted by pages.
Sorting is comparing in pairs, and someone has to answer.
Comparable is the natural order, inside the class. There is only one.
Comparator supplies other orders from outside, as many as needed.
Sorting is comparing in pairs, and someone has to answer. Comparable is the natural order, inside the class. There is only one. Comparator supplies other orders from outside, as many as needed.