From all of the sort method examples i've seen, i have never come across one where they pass in a definition of a Comparator. If the comparator is designed to return a negative, positive or 0 to sort the objects, what does the sort method do with this information? How does the sort method obtain meaningful information from the Comparator definition and perform its operation?
Here is the sort method in question:
public void sort() {
library.sort(new BookComparator());
}
Here is the entire Comparator class:
import java.util.Comparator;
public class BookComparator implements Comparator<Book> {
public int compare(Book a, Book b) {
if(a == null || b == null) {
throw new NullPointerException();
}
int result = 0 ;
if(a.getAuthor() == null) {
if(b.getAuthor() != null) {
result = -1;
}
} else if(b.getAuthor() == null) {
result = 1;
} else {
result = a.getAuthor().compareTo(b.getAuthor());
}
if(result !=0) {
return result;
}
if(a.getTitle() == null) {
if(b.getTitle() != null) {
result = -1;
}
} else if(b.getTitle() == null) {
result = 1;
} else {
result = a.getTitle().compareTo(b.getTitle());
}
if(result !=0) {
return result;
}
if(a.getYear() < b.getYear()){
return -1;
} else if (a.getYear() == b.getYear()){
return 0;
} else {
return 1;
}
}
}