Name

Collator

Synopsis

This class compares, orders, and sorts strings in a way appropriate for the default locale or some other specified locale. Because it is an abstract class, it cannot be instantiated directly. Instead, you must use the static getInstance( ) method to obtain an instance of a Collator subclass that is appropriate for the default or specified locale. You can use getAvailableLocales( ) to determine whether a Collator object is available for a desired locale.

Once an appropriate Collator object has been obtained, you can use the compare( ) method to compare strings. The possible return values of this method are -1, 0, and 1, which indicate, respectively, that the first string is collated before the second, that the two are equivalent for collation purposes, and that the first string is collated after the second. The equals( ) method is a convenient shortcut for testing two strings for collation equivalence.

When sorting an array of strings, each string in the array is typically compared more than once. Using the compare( ) method in this case is inefficient. A more efficient method for comparing strings multiple times is to use getCollationKey( ) for each string to create CollationKey objects. These objects can then be compared to each other more quickly than the strings themselves can be compared.

You can customize the way the Collator object performs comparisons by calling setStrength( ). If you pass the constant PRIMARY to this method, the comparison looks only ...

Get Java in a Nutshell, 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.