// Display the elements.
for(String element : ts)
System.out.print(element + " ");
System.out.println();
}
}
As the following output shows, the tree is now stored in reverse order:
FEDCBA
Look closely at the MyComp class, which implements Comparator and overrides
compare( ). (As explained earlier, overriding equals( ) is neither necessary nor common.)
Inside compare( ), the String method compareTo( ) compares the two strings. However, bStr--
not aStr--invokes compareTo( ). This causes the outcome of the comparison to be reversed.
For a more practical example, the following program is an updated version of the TreeMap
program shown earlier that stores account balances. In the previous version, the accounts
were sorted by name, but the sorting began with the first name. The following program sorts
the accounts by last name. To do so, it uses a comparator that compares the last name of each
account. This results in the map being sorted by last name.
// Use a comparator to sort accounts by last name.
import java.util.*;
// 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.
}
class TreeMapDemo2 {
public static void main(String args[]) {
// Create a tree map.
TreeMap<String, Double> tm = new TreeMap<String, Double>(new TComp());
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home