String's equals method isn't always enough
I read Ethan Nicholas' blog about intern'd strings with great interest. I agree with his assessment that using '==' to compare String objects is almost never correct. He suggests that String's
equals method is superior. His description of the
intern method is excellent, and I wouldn't want to detract from his comments. He is right on...the
equals method is the right way to compare many strings. However, I think you need to know more about string comparisons, especially why
equals does not provide the correct results all the time.
The Problem with String's equals
The problem shows up when you want to compare text linguistically...like you do when you use a standard word dictionary. The
String class just doesn't have the ability to compare text with natural language in mind. String's
compareTo methods compare the individual
char values in the string. If the
char value at index n in string1 == the
char value at index n in string2 for all n in both strings, the
equals method returns
true. So what's the problem?
The problem is that there are often multiple ways to represent the same text in Unicode. For example, the name "Mich