The Comparable Interface Type
The Comparator interface type
- How can we sort countries by name?
- Can't implement Comparable twice!
- Comparator interface type gives added flexibility
public interface Comparator
{
int compare(Object object1, Object object2);
}
- Pass comparator object to sort:
Collections.sort(list, comp);
- CountryComparatorByName.java
ComparatorTest.java
- Comparator object is a function object
- This particular comparator object has no state
- State can be useful, e.g. flag to sort in ascending or descending
order
Anonymous Classes
- No need to name objects that are used only once
Collections.sort(countries,
new CountryComparatorByName());
- No need to name classes that are used only once
Comparator comp = new
Comparator()
{
public int compare(Object obj1, Object obj2)
{
Country country1 = (Country)obj1;
Country country2 = (Country)obj2;
return country1.getName().compareTo(country2.getName());
}
};
Anonymous Classes
- anonymous new expression:
- defines anonymous class that implements Comparator
- defines compare method of that class
- constructs one object of that class
- Cryptic syntax for very useful feature
Anonymous Classes
- Commonly used in factory methods:
public static Comparator
comparatorByName()
{
return new Comparator()
{
public int compare(Object o1, Object o2)
{ . . . }
};
}
- Collections.sort(a,
Country.comparatorByName());
- Neat arrangement if multiple comparators make sense
(by name, by area, ...)
See: ComparatorTest2.java
Maintained by John Loomis,
updated Thu Feb 22 22:30:04 2007