当我检查String
的私有内部类CaseInsensitiveComparator
的实现时,我发现了一些奇怪的事情。
private static class CaseInsensitiveComparator
implements Comparator<String>, java.io.Serializable {
...
public int compare(String s1, String s2) {
int n1 = s1.length();
int n2 = s2.length();
int min = Math.min(n1, n2);
for (int i = 0; i < min; i++) {
char c1 = s1.charAt(i);
char c2 = s2.charAt(i);
if (c1 != c2) {
c1 = Character.toUpperCase(c1);
c2 = Character.toUpperCase(c2);
if (c1 != c2) {
c1 = Character.toLowerCase(c1);
c2 = Character.toLowerCase(c2);
if (c1 != c2) {
// No overflow because of numeric promotion
return c1 - c2;
}
}
}
}
return n1 - n2;
}
...
}
我很好奇的是:在for
循环中,一旦比较了大写字符,为什么还要再次比较小写字符呢?当Character.toUpperCase(c1)
和Character.toUpperCase(c2)
不同时,Character.toLowerCase(c1)
和Character.toLowerCase(c2)
是否可能相等?
难道不能这样简化吗?
public int compare(String s1, String s2) {
int n1 = s1.length();
int n2 = s2.length();
int min = Math.min(n1, n2);
for (int i = 0; i < min; i++) {
char c1 = s1.charAt(i);
char c2 = s2.charAt(i);
if (c1 != c2) {
c1 = Character.toUpperCase(c1);
c2 = Character.toUpperCase(c2);
if (c1 != c2) {
// No overflow because of numeric promotion
return c1 - c2;
}
}
}
return n1 - n2;
}
我错过了什么吗?
发布于 2015-07-29 17:18:45
有些Unicode字符的小写形式不同,但具有相同的大写形式。例如,希腊字母Sigma - it有两种小写形式(σ和ς,仅在单词末尾使用),但只有一种大写形式(Σ)。
我找不到任何相反的例子,但是如果将来发生这样的情况,当前的Java实现已经为此做好了准备。您的Comparator
版本肯定能正确处理Sigma案例。
您可以在Unicode网站上的Case Mapping FAQ中找到更多信息。
https://stackoverflow.com/questions/31696168
复制相似问题