简体   繁体   中英

How do I use java.util.Locale as a key somewhere?

java.util.Locale is one of those classes where I wonder whether I'm too stupid or the guy who wrote it. Is Mark Davis around?

As far as I can see, this class isn't supposed to be used. The internal cache in the class is private. The factory package private. equals() uses == to compare strings. This means that I can't compare instances of the class for equality unless I create instances myself, put them into a cache somewhere, violating DRY.

Is this what I should do? Is there a sane explanation for this behavior???

This happens because all String s passed to the constructors are intern() -ed. A questionable practice, but the behaviour is correct in the end.


The 3-argument constructor is

public Locale(String language, String country, String variant) {
    this.language = convertOldISOCodes(language);
    this.country = toUpperCase(country).intern();
    this.variant = variant.intern();
}

and then later on

private String convertOldISOCodes(String language) { 
    // we accept both the old and the new ISO codes for the languages whose ISO 
    // codes have changed, but we always store the OLD code, for backward compatibility 
    language = toLowerCase(language).intern(); 

You can always use locale.toString() for putting in maps in order to work this around.

Or you can wrap your Locale ( class LocaleWrapper { private Locale locale; .. } ), implement the equals method properly and then use the wrapper.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM