I wanted to write my own compareTo method, so I wrote this simple code:
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;
}
}
Well, this code is working ok, but I hate the last if/else
statement- do you have any suggestions how to improve this code?