|
|
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Sorting long lists of strings is often time consuming. If your sort algorithm compares strings repeatedly, you can speed up the process by using theCollationKeyclass.A
CollationKeyobject represents a sort key for a given
StringandCollator. Comparing twoCollationKeyobjects involves a bitwise comparison of sort keys and is faster than comparingStringobjects with theCollator.comparemethod. However, generatingCollationKeyobjects requires time. Therefore if aStringis to be compared just once,Collator.compareoffers better performance.The example that follows uses a
CollationKeyobject to sort an array of words. Source code for this example is inKeysDemo.java.
The
KeysDemoprogram creates an array ofCollationKeyobjects in themainmethod. To create aCollationKey, you invoke thegetCollationKeymethod on aCollatorobject. You cannot compare twoCollationKeyobjects unless they originate from the sameCollator. Themainmethod is as follows:static 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); }The
sortArraymethod invokes theCollationKey.compareTomethod. ThecompareTomethod 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 theCollationKeyobjects, not theStringobjects from the original array of words. Here is the code for thesortArraymethod:public static void sortArray(CollationKey[] keys) { CollationKey tmp; for (int i = 0; i < keys.length; i++) { for (int j = i + 1; j < keys.length; j++) { if (keys[i].compareTo(keys[j]) > 0) { tmp = keys[i]; keys[i] = keys[j]; keys[j] = tmp; } } } }The
KeysDemoprogram sorts an array ofCollationKeyobjects, but the original goal was to sort an array ofStringobjects. To retrieve theStringrepresentation of eachCollationKey, the program invokesgetSourceStringin thedisplayWordsmethod, as follows:static void displayWords(CollationKey[] keys) { for (int i = 0; i < keys.length; i++) { System.out.println(keys[i].getSourceString()); } }The
displayWordsmethod prints the following lines:apricot grape lemon peach
|
|
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2004 Sun Microsystems, Inc. All rights reserved.