Comparable Interface
Objects that have an ordering are compared using the compareTo() method.
10. First Differing Pair of Characters
Answer:
"bugbear" .compareTo ("bugbear") zero "bug" .compareTo ("bugbear") negative "pepper" .compareTo ("peppermint") negative "toadstool" .compareTo ("toad") positive "cat" .compareTo ("caterpillar") negative
First Differing Pair of Characters
The remaining case is the difficult one. Say that two strings are not identical, and one is not the prefix of the other. Then there must be at least one character in one string that is different from a character at the same position in the other string:
first differing characters are 'a' and 'e'
beat
|
beet
first differing characters are 'r' and 'h'
bear rug
|
bear hug
first differing characters are 'c' and 'm'
batcave
||||
batmobile
first differing characters are 'b' and 'B'
baseball bat
| |
baseBall hat
Find the first pair of differing characters. The result of compareTo()
is based on just that pair.
Rule 3: Find the first differing pair of characters in the strings A
and B
. Call them Achar
and Bchar
. Then A.compareTo(B)
is negative if Achar
comes before Bchar
in the alphabet that Java uses (and otherwise is positive).
This rule compares just two characters. For characters of the same case, the one that comes earlier in the alphabet that Java uses is less than the other. For characters of different case, all upper case characters are less than all lower case characters.
The lengths of the two strings do not matter. Merely find the first differing pair of characters, and base the result on them.
Question 10:
Decide on the following:
Comparison Zero, Positive, or Negative "bugbear" .compareTo ("Bugbear") "rugrat" .compareTo ("rugRat") "ant" .compareTo ("turtle") "toadstool" .compareTo ("total") "ABCDEFG" .compareTo ("ABcD") "roadrunner" .compareTo ("roadkill")