Java Reference
In-Depth Information
return getClass() == comparator.getClass();
}
}
Directory "TrySortingWithComparator"
Just to make it more interesting and to demonstrate that it's this comparator and not the compareTo()
method in the Person class that's being used by the sort() method, this comparator establishes a des-
cending sequence of Person objects. By switching the sign of the value that the compareTo() method
returns, you invert the sort order. Thus, sorting using this comparator sorts Person objects in descending
alphabetical order by surname and then by first name within surname.
You can try this out with the following program:
import java.util.Arrays;
public class TrySortingWithComparator {
public static void main(String[] args) {
Person[] authors = {
new Person("Danielle", "Steel"),
new Person("John",
"Grisham"),
new Person("Tom", "Clancy"),
new Person("Christina",
"Schwartz"),
new Person("Patricia", "Cornwell"), new Person("Bill", "Bryson")
};
System.out.println("Original order:");
for(Person author : authors) {
System.out.println(author);
}
Arrays.sort(authors, new ComparePersons()); // Sort using
comparator
System.out.println("\nOrder after sorting using comparator:");
for(Person author : authors) {
System.out.println(author);
}
Arrays.sort(authors);
// Sort using
compareTo() method
System.out.println("\nOrder after sorting using compareTo()
method:");
for(Person author : authors) {
System.out.println(author);
}
}
Search WWH ::




Custom Search