Working with Text |
Sorting long lists of strings is often time consuming. If your sort algorithm compares strings repeatedly you can speed up the process by using theCollationKey
class.A
CollationKey
object represents a sort key for a givenString
andCollator
. Comparing twoCollationKey
objects involves a bitwise comparison of sort keys, and is faster than comparingString
objects with theCollator.compare
method. However, generatingCollationKey
objects requires time. Therefore, if aString
is to be compared just once,Collator.compare
offers better performance.The example that follows uses a
CollationKey
object to sort an array of words. The source code for this example is in the file namedKeysDemo.java
.The
KeysDemo
program creates an array ofCollationKey
objects in themain
method. To create aCollationKey
, you invoke thegetCollationKey
method upon aCollator
object. You cannot compare twoCollationKey
objects unless they originate from the sameCollator
. Themain
method is as follows:Thestatic public void main(String[] args) { Collator enUSCollator = Collator.getInstance(new Locale("en","US")); String [] words = { "peach", "apricot", "grape", "lemon" }; CollationKey[] keys = new CollationKey[words.length]; for (int k = 0; k < keys.length; k ++) { keys[k] = enUSCollator.getCollationKey(words[k]); } sortArray(keys); printArray(keys); }sortArray
method invokes theCollationKey.compareTo
method. ThecompareTo
method returns an integer less than, equal to, or greater than zero if thekeys[i]
object is less than, equal to, or greater than thekeys[j]
object. Note that the program compares theCollationKey
objects, not theString
objects from the original array of words. Here is the code for thesortArray
method:Thepublic static void sortArray(CollationKey[] keys) { CollationKey tmp; for (int i = 0; i < keys.length; i++) { for (int j = i + 1; j < keys.length; j++) { // Compare the keys if( keys[i].compareTo( keys[j] ) > 0 ) { // Swap keys[i] and keys[j] tmp = keys[i]; keys[i] = keys[j]; keys[j] = tmp; } } } }KeysDemo
program sorts an array ofCollationKey
objects, but the original goal was to sort an array ofString
objects. To retrieve theString
representation of eachCollationKey
, the program invokesgetSourceString
in thedisplayWords
method:Thestatic void displayWords(CollationKey[] keys) { for (int i = 0; i < keys.length; i++) { System.out.println(keys[i].getSourceString() + " "); } }displayWords
method prints the following lines:apricot grape lemon peach
Working with Text |