Internationalization and localization tools


Locale-Sensitive Java Method

java.text.Collator

public static Collator getInstance()

public static Collator getInstance(
   Locale locale)

Internationalization (I18n) Method Overview

The Collator class performs locale-sensitive String comparison. You use this class to build searching and sorting routines for natural language text when you want the resulting lists to be sorted in a locale-sensitive fashion as opposed to the binary sort that is provided through use of java.lang.String.compareTo.

The zero-argument factory method Collator.getInstance() performs the collation according to the rules of the default locale.

I18n Issues

The default locale is not always the correct locale for all users. It is recommended I18n practice to call the static factory method that accepts a Locale object as an argument to ensure that the strings are sorted according to the current user's locale and not just according to the system's locale. In cases of web applications where the Java code is run on a server but the results displayed on JSP page on another machine, the locale of the server is frequently not that of the jsp-page viewer. It is better to retrieve the user's locale from the session, for example, and then pass it into the factory method.

Globalyzer will detect this method and report it as an I18n issue regardless of the signature used and regardless of whether it is being used correctly. If Locale is already being passed as an argument, Globalyzer will detect it to force developers to double check that the correct Locale is being passed. If you have determined that the call is being handled correctly, you can use Globalyzer's Ignore Comment functionality to ensure that it isn't picked up in a subsequent scan.

Suggested Replacement

public static Collator getInstance(
   Locale desiredLocale)

Instead of:

// Compare two strings in the default locale
Collator myCollator = Collator.getInstance();
if( myCollator.compare("abc", "ABC") < 0 )
    System.out.println(
    "abc is less than ABC");
else
    System.out.println(
    "abc is greater than or equal to ABC");

Use:

//retrieve the runtime user's locale
Locale locale = new Locale(getUserLocale());
//pass the user's locale as an argument
Collator myCollator = Collator.getInstance(locale);
if( myCollator.compare("abc", "ABC") < 0 )
    System.out.println(
    "abc is less than ABC");
else
    System.out.println(
    "abc is greater than or equal to ABC");

Please see Java Collation for more information.

Locale-Sensitive Java Methods

 

Lingoport internationalization and localization services and software