Ami*_*mir 18 java sorting locale collation
使用数字对字符串进行排序的方式与一种语言不同.例如,英文数字在升序排序中位于字母之前.但是,在德语中,数字是在字母之后排序的.
我尝试使用Collator
以下方法对字符串进行排序:
private Collator collator = Collator.getInstance(Locale.GERMANY);
collator.compare(str1, str2)
Run Code Online (Sandbox Code Playgroud)
但是上面的比较没有考虑字母后的数字规则.
有没有人知道为什么Java在我使用的时候没有考虑这个规则(字母后面的数字)RuleBasedCollator
,如下所示:
private final String sortOrder = "< a, A < b, B < c, C < d, D < e, E < f, F < g, G < h, H < i, I < j, J < k, K < l, L < m, M < n, N < o, O < p, P < q, Q < r, R < s, S < t, T < u, U < v, V < w, W < x, X < y, Y < z, Z < 0 < 1 < 2 < 3 < 4 < 5 < 6 < 7 < 8 < 9";
private Collator collator = new RuleBasedCollator(sortOrder);
Run Code Online (Sandbox Code Playgroud)
Jas*_*per 13
您可以检查/调试源代码,看看为什么没有变化:
Collator.getInstance(Locale.GERMANY);
Run Code Online (Sandbox Code Playgroud)
调用以下部分代码:
public static synchronized
Collator getInstance(Locale desiredLocale)
{
// Snipping some code here
String colString = "";
try {
ResourceBundle resource = LocaleData.getCollationData(desiredLocale);
colString = resource.getString("Rule");
} catch (MissingResourceException e) {
// Use default values
}
try
{
result = new RuleBasedCollator( CollationRules.DEFAULTRULES +
colString,
CANONICAL_DECOMPOSITION );
}
// Snipping some more code here
Run Code Online (Sandbox Code Playgroud)
在这里,你可以看到,具体规则(colString
里面是空的,你的情况是这样)放置后的默认设置(CollationRules.DEFAULTRULES
).
正如您已经发现默认值首先放置数字:
// NUMERICS
+ "<0<1<2<3<4<5<6<7<8<9"
+ "<\u00bc<\u00bd<\u00be" // 1/4,1/2,3/4 fractions
// NON-IGNORABLES
+ "<a,A"
+ "<b,B"
+ "<c,C"
+ "<d,D"
Run Code Online (Sandbox Code Playgroud)