如何手动词典比较到#ab;" &安培; "" ABCDE"有效

时间:2016-07-12 07:46:25

标签: java compareto lexicographic

我想编写自己的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声明 - 您对如何改进此代码有任何建议吗?

1 个答案:

答案 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;
}