Java Reference
In-Depth Information
TRY IT OUT: Sorting an Array Using a Comparator
You can borrow the version of the
Person
class that implements the
Comparable<>
interface from the
TryVector
example in Chapter 14 for this example. Copy the
Person.java
file to the directory you set
up for this example. The comparator needs access to the first name and the surname for a
Person
object
to make comparisons, so you need to add methods to the
Person
class to allow that:
public class Person implements Comparable<Person> {
public String getFirstName() {
return firstName;
}
public String getSurname() {
return surname;
}
// Rest of the class as before...
}
Directory "TrySortingWithComparator"
You can now define a class for a comparator that applies to
Person
objects:
import java.util.Comparator;
public class ComparePersons implements Comparator<Person> {
// Method to compare Person objects - order is descending
public int compare(Person person1, Person person2) {
int result =
-person1.getSurname().compareTo(person2.getSurname());
return result == 0 ?
-person1.getFirstName().compareTo(person2.getFirstName()) :
result;
}
// Method to compare with another comparator
public boolean equals(Object comparator) {
if(this == comparator) {
// If argument is the same
object
return true;
// then it must be equal
}
if(comparator == null) {
// If argument is null
return false;
// then it can't be equal
}
// Class must be the same for equal