Java Reference
In-Depth Information
}
Directory "TrySortingWithComparator"
This example produces the following output:
Original order:
Danielle Steel
John Grisham
Tom Clancy
Christina Schwartz
Patricia Cornwell
Bill Bryson
Order after sorting using comparator:
Danielle Steel
Christina Schwartz
John Grisham
Patricia Cornwell
Tom Clancy
Bill Bryson
Order after sorting using compareTo() method:
Bill Bryson
Tom Clancy
Patricia Cornwell
John Grisham
Christina Schwartz
Danielle Steel
How It Works
After defining the
authors
array of
Person
objects, you sort them with the statement:
Arrays.sort(authors, new ComparePersons()); // Sort using
comparator
The second argument is an instance of the
ComparePersons
class, which is a comparator for
Person
objects because it implements the
Comparator<Person>
interface. The
sort()
method calls the
com-
pare()
method to establish the order between
Person
objects, and you defined this method like this:
public int compare(Person person1, Person person2) {
int result =
-person1.getSurname().compareTo(person2.getSurname());
return result == 0 ?
-person1.getFirstName().compareTo(person2.getFirstName()):
result;
}
The primary comparison is between surnames and returns a result that is the opposite of that produced by
the
compareTo()
method for
String
objects. Because the order established by the
compareTo()
method