1

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?

Nimrod
  • 1,100
  • 1
  • 11
  • 27

1 Answers1

3

That depends on how much of it you want to write yourself. You could use

return a.length() - b.length(); // as length is non-negative

or

return Integer.compareTo(a.length(), b.length());

In your first loop you could also write

for (int i = 0; i < a.length() && i < b.length(); i++) {
    int diff = a.charAt(i) - b.charAt(i);
    if (diff != 0)
        return diff;
}
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • @AndyTurner yes but `char - char` is an `int` as is a `byte - byte` or `byte % byte` :P – Peter Lawrey Jul 12 '16 at 07:50
  • Yeah, realized that after I wrote it. I still prefer the `WrappedPrimitive.compare` methods, mind you. – Andy Turner Jul 12 '16 at 07:51
  • @AndyTurner I often wonder why programmers are so afraid of basic math that far more complex expressions are appealing. – Peter Lawrey Jul 12 '16 at 07:53
  • 1
    The reason I had drummed into me is to avoid problems with the subtraction overflowing. I guess that you've not got that problem with the "shorter than an `int`" types; but I suppose I've just got that "use compare" pattern imprinted. Just another thing to unlearn, I suppose. – Andy Turner Jul 12 '16 at 07:56
  • 1
    @AndyTurner when you are a beginner you break all the rules because you don't know what they are, as you become a senior developer you have to learn the rules, as you become an expert you know when breaking a rule makes sense, and you should be aware that some will see this as breaking a rule which is a good time to comment why it was done. – Peter Lawrey Jul 12 '16 at 08:33