INTER.SE
The 'equals()' method of strings should not be used in an internationalized environment
Description
This rule flags code that uses the `equals()' method of strings.
If code uses the `equals()' method of strings, it will not run in an internationalized environment because it performs binary comparisons of the Unicode characters within the two strings, which are ineffective when sorting in most languages.
A string variable with '.equals()' cannot be relied on to sort strings. This is because the Unicode values of the characters in the strings do not correspond to the relative order of the characters for most languages.
Example
package INTER;
public class SE{
public boolean eqstr(){
String s1= new String("hello");
String s2 = new String("bye");
if (s1.equals(s2)) // violation
return true;
return false;
}
}
Repair
The predefined collation rules provided by the "Collator" class should be used instead to sort strings in a locale-independent manner. To instantiate the "Collator" class, invoke the getInstance method. Usually, you create a Collator for the default Locale, as in the following example :
Collator myCollator = Collator.getInstance();
You can also specify a particular Locale when you create a Collator, as follows:
Collator myFrenchCollator = Collator.getInstance(Locale.FRENCH);
Then you invoke the Collator.equals method to perform a locale-independent string comparison as follows:
boolean is_equal = myCollator.equals(s1,s2);
Reference
http://java.sun.com/docs/books/tutorial/i18n/intro/checklist.html
http://java.sun.com/docs/books/tutorial/i18n/text/locale.html
|