Java Reference
In-Depth Information
Example 2•9: Sorter.java (continued)
for(int i = 0; i < a.length; i++) b[i] = a[i].toLowerCase();
// Sort that secondary array, and rearrange the original array
// in exactly the same way, resulting in a case-insensitive sort.
// Note the use of the ascii_comparer object
sort(b, a, from, to, up, ascii_comparer);
}
/**
* Sort an array of strings into ascending order, using the correct
* collation order for the default locale
**/
public static void sort(String[] a) {
sort(a, 0, a.length-1, true, false, null);
}
/**
* Sort a portion of an array of strings, using the collation order of
* the default locale. If up is true, sort ascending, otherwise, sort
* descending. If ignorecase is true, ignore the capitalization of letters
**/
public static void sort(String[] a, int from, int to,
boolean up, boolean ignorecase) {
sort(a, from, to, up, ignorecase, null);
}
/**
* Sort a portion of an array of strings, using the collation order of
* the specified locale. If up is true, sort ascending, otherwise, sort
* descending. If ignorecase is true, ignore the capitalization of letters
**/
public static void sort(String[] a, int from, int to,
boolean up, boolean ignorecase,
Locale locale) {
// Don't sort if we don't have to
if ((a == null) || (a.length < 2)) return;
// The java.text.Collator object does internationalized string compares
// Create one for the specified, or the default locale.
Collator c;
if (locale == null) c = Collator.getInstance();
else c = Collator.getInstance(locale);
// Specify whether or not case should be considered in the sort.
// Note: this option does not seem to work correctly in JDK 1.1.1
// using the default American English locale.
if (ignorecase) c.setStrength(Collator.SECONDARY);
// Use the Collator object to create an array of CollationKey objects
// that correspond to each of the strings.
// Comparing CollationKeys is much quicker than comparing Strings
CollationKey[] b = new CollationKey[a.length];
for(int i = 0; i < a.length; i++) b[i] = c.getCollationKey(a[i]);
// Now define a Comparer object to compare collation keys, using an
// anonymous class.
Comparer comp = new Comparer() {
public int compare(Object a, Object b) {
return ((CollationKey)a).compareTo((CollationKey)b);
Search WWH ::




Custom Search