The Java Tutorials have been written for JDK 8.Java教程是为JDK 8编写的。Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available.本页中描述的示例和实践没有利用后续版本中引入的改进,并且可能使用不再可用的技术。See Java Language Changes for a summary of updated language features in Java SE 9 and subsequent releases.有关Java SE 9及其后续版本中更新的语言特性的摘要,请参阅Java语言更改。
See JDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases.有关所有JDK版本的新功能、增强功能以及已删除或不推荐的选项的信息,请参阅JDK发行说明。
Applications that sort through text perform frequent string comparisons. For example, a report generator performs string comparisons when sorting a list of strings in alphabetical order.
If your application audience is limited to people who speak English, you can probably perform string comparisons with the String.compareTo
method. The String.compareTo
method performs a binary comparison of the Unicode characters within the two strings. For most languages, however, this binary comparison cannot be relied on to sort strings, because the Unicode values do not correspond to the relative order of the characters.
Fortunately the Collator
class allows your application to perform string comparisons for different languages. In this section, you'll learn how to use the Collator
class when sorting text.
Collation rules define the sort sequence of strings. These rules vary with locale, because various natural languages sort words differently. Using the predefined collation rules provided by the Collator
class, you can sort strings in a locale-independent manner.
In some cases, the predefined collation rules provided by the Collator
class may not work for you. For example, you may want to sort strings in a language whose locale is not supported by Collator
. In this situation, you can define your own collation rules, and assign them to a RuleBasedCollator
object.
With the CollationKey
class, you may increase the efficiency of string comparisons. This class converts String
objects to sort keys that follow the rules of a given Collator
.