D
djdsz
Unregistered / Unconfirmed
GUEST, unregistred user!
在java.lang包的String.java中有如下的语句,是比较两个字符串(不区分大小写)的:
public int compare(Object o1, Object o2) {
String s1 = (String) o1;
String s2 = (String) o2;
int n1=s1.length(), n2=s2.length();
for (int i1=0, i2=0;
i1<n1 &&
i2<n2;
i1++, i2++) {
char c1 = s1.charAt(i1);
char c2 = s2.charAt(i2);
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)
return c1 - c2;
}
}
}
return n1 - n2;
}
请各位说说注释部分为什么要那样写。
public int compare(Object o1, Object o2) {
String s1 = (String) o1;
String s2 = (String) o2;
int n1=s1.length(), n2=s2.length();
for (int i1=0, i2=0;
i1<n1 &&
i2<n2;
i1++, i2++) {
char c1 = s1.charAt(i1);
char c2 = s2.charAt(i2);
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)
return c1 - c2;
}
}
}
return n1 - n2;
}
请各位说说注释部分为什么要那样写。