Java Reference
In-Depth Information
ordering on objects of any class. Typically, the Java API dealing with a collection of objects requires a Comparator
object to specify a custom ordering. The Comparator interface is a generic interface.
public interface Comparator<T> {
int compare(T o1, T o2);
boolean equals(Object obj);
// Default and static methods are not shown here
}
The Comparator interface has been overhauled in Java 8. Several static and default methods have been added
to the interface. I will discuss some of the new methods in this chapter and some later in the chapter on lambda
expressions.
Typically, you do not need to implement the equals() method of the Comparator interface. Every class in Java
inherits the equals() method from the Object class and that is fine in most cases. The compare() method takes two
parameters and it returns an integer. It returns a negative integer, zero, or a positive integer if the first argument is less
than, equal to, or greater than the second argument, respectively.
Listing 17-35 and Listing 17-36 contain two implementations of the Comparator interface: one compares two
ComparablePerson objects based on their first name and another based on their last names.
Listing 17-35. A Comparator Comparing ComparablePersons Based on Their First Names
// FirstNameComparator.java
package com.jdojo.interfaces;
import java.util.Comparator;
public class FirstNameComparator implements Comparator<ComparablePerson> {
public int compare(ComparablePerson p1, ComparablePerson p2) {
String firstName1 = p1.getFirstName();
String firstName2 = p2.getFirstName();
int diff = firstName1.compareTo(firstName2);
return diff;
}
}
Listing 17-36. A Comparator Comparing ComparablePersons Based on Their Last Names
// LastNameComparator.java
package com.jdojo.interfaces;
import java.util.Comparator;
public class LastNameComparator implements Comparator<ComparablePerson> {
public int compare(ComparablePerson p1, ComparablePerson p2) {
String lastName1 = p1.getLastName();
String lastName2 = p2.getFirstName();
int diff = lastName1.compareTo(lastName2);
return diff;
}
}
 
Search WWH ::




Custom Search