如何在某处使用 java.util.Locale 作为键?

Aar*_*lla 5 java locale equality

java.util.Locale是其中一门课,我想知道是我太蠢还是写它的人太蠢。马克·戴维斯在吗?

据我所知,这个类不应该被使用。类中的内部缓存是私有的。工厂包私人。equals()用于==比较字符串。这意味着我无法比较类的实例是否相等,除非我自己创建实例,将它们放入某处的缓存中,从而违反了 DRY。

这是我应该做的吗?这种行为有合理的解释吗???

Rob*_*anu 4

发生这种情况是因为String传递给构造函数的所有 s 都经过了intern()-ed。这是一种值得怀疑的做法,但这种行为最终是正确的。


3 参数构造函数是

public Locale(String language, String country, String variant) {
    this.language = convertOldISOCodes(language);
    this.country = toUpperCase(country).intern();
    this.variant = variant.intern();
}
Run Code Online (Sandbox Code Playgroud)

然后后来

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(); 
Run Code Online (Sandbox Code Playgroud)