Java Reference
In-Depth Information
fore "acz" because b comes before z. But the Unicode characters are dif-
ferent c ( \u0063 ) comes before ç ( \u00e7 ) in the Unicode character setso
these strings will actually sort the other way around. Internationaliza-
tion and localization are discussed in Chapter 24 .
The first compare operation is equals , which returns true if it is passed
a reference to a String object having the same contentsthat is, the two
strings have the same length and exactly the same Unicode charac-
ters. If the other object isn't a String or if the contents are different,
String.equals returns false . As you learned on page 100 , this overrides
Object.equals to define equivalence instead of identity.
To compare strings while ignoring case, use the equalsIgnoreCase meth-
od. By "ignore case," we mean that Ë and ë are considered the same
but are different from E and e . Characters with no case distinctions, such
as punctuation, compare equal only to themselves. Unicode has many
interesting case issues, including a notion of "titlecase." Case issues in
String are handled in terms of the case-related methods of the Character
class, as described in " Character " on page 192 .
A String can be compared with an arbitrary CharSequence by using the
contentEquals method, which returns true if both objects represent ex-
actly the same sequence of characters.
To sort strings, you need a way to order them, so String implements
the interface Comparable<String> the Comparable interface was described
on page 118 . The compareTo method returns an int that is less than,
equal to, or greater than zero when the string on which it is invoked
is less than, equal to, or greater than the other string. The ordering
used is Unicode character ordering. The String class also defines a com-
pareToIgnoreCase method.
The compareTo method is useful for creating an internal canonical order-
ing of strings. A binary search, for example, requires a sorted list of ele-
ments, but it is unimportant that the sorted order be local language or-
der. Here is a binary search lookup method for a class that has a sorted
array of strings:
 
Search WWH ::




Custom Search