Compare()
int compare(T obj1, T obj2)
- Compare obj1 to obj2 (obj1 - obj2)
Returns zero if obj1 = obj2
Returns positive if obj1 > obj2
Returns negative if obj1 < obj2
ClassCastException if the types of the objects are not compatible
Customize Comparator
By overriding compare()
Basic example:
// A reverse comparator for strings.
class MyComp implements Comparator<String> {
public int compare(String a, String b) {
String aStr, bStr;
aStr = a;
bStr = b;
// Reverse the comparison.
return bStr.compareTo(aStr);
}
// No need to override equals.
}
-
Create a custom class implementing Comparator and overrides compare( )
-
String method compareTo( ) compares the two strings
TreeMap example:
// Compare last whole words in two strings.
class TComp implements Comparator<String> {
public int compare(String a, String b) {
int i, j, k;
String aStr, bStr;
aStr = a;
bStr = b;
// Find index of beginning of last name.
i = aStr.lastIndexOf(' ');
j = bStr.lastIndexOf(' ');
k = aStr.substring(i).compareTo(bStr.substring(j));
if(k==0) // last names match, check entire name
return aStr.compareTo(bStr);
else
return k; }
// No need to override equals.
}
// Create a tree map with the new comparator
TreeMap<String, Double> tm = new TreeMap<String, Double>(new TComp());
// Insert in the sorted order
tm.put("John Doe", new Double(3434.34));
tm.put("Tom Smith", new Double(123.22));
tm.put("Jane Baker", new Double(1378.00));
tm.put("Tod Hall", new Double(99.22));
tm.put("Ralph Smith", new Double(-19.08));
-
TComp compares two strings that hold first and last names.
-
This yields a tree map that is sorted by last name, and within last name by first name.
Array.sort example:
// intervals: int[][], where intervals[i] = [starti, endi]
// sort the intervals by starti
Arrays.sort(intervals, new Comparator<int[]>() {
public int compare(int[] a, int[] b) {
int aStart, bStart;
aStart = a[0];
bStart = b[0];
return aStart-bStart;
}
});