我想编写自己的compareTo方法,所以我编写了这个简单的代码:
public int myCompare(String a, String b) {
int min = Math.min(a.length(), b.length());
for (int i=0; i < min; i++) {
int diff = a.charAt(i) - b.charAt(i);
if (diff == 0) {
continue;
} else {
return diff;
}
}
// meaning both strings are equals so far
if (a.length() == b.length()) {
return 0;
} else if (a.length() > b.length()) {
return -1;
} else {
return 1;
}
}
嗯,这段代码工作正常,但我讨厌上一篇if/else
声明 - 您对如何改进此代码有任何建议吗?
答案 0 :(得分:3)
这取决于你想要自己写多少。你可以用
return a.length() - b.length(); // as length is non-negative
或
return Integer.compareTo(a.length(), b.length());
在你的第一个循环中你也可以写
for (int i = 0; i < a.length() && i < b.length(); i++) {
int diff = a.charAt(i) - b.charAt(i);
if (diff != 0)
return diff;
}