Reputation: 13
if (value.compareTo(elementData[size]) >= 0) {
elementData[size + 1] = value;
size++;
} else if (value.compareTo(elementData[0]) <= 0) {
for (int i = size; i >= 0; i--) {
elementData[i + 1]= elementData[i];
}
elementData[0] = value;
size++;
}
The very first if statement should return a positive number from the compareTo. I've debugged and confirmed that it does return a positive number however it doesn't enter the block.
I'm comparing strings that like these "str1" "str2"... etc. It works fine until I get to "str10" and have to compare it to "str9". It's saying that "str10" is less than "str9" does that make any sense?
It happens every 10 iterations. So my array looks like [str0, str1, str10...str19,str2, str20, str21, ... str29..etc]
Upvotes: 1
Views: 80
Reputation: 56469
consider how the string
values are compared when using compareTo(String anotherString).
Compares two strings lexicographically. The comparison is based on the Unicode value of each character in the strings. The character sequence represented by this String object is compared lexicographically to the character sequence represented by the argument string. The result is a negative integer if this String object lexicographically precedes the argument string. The result is a positive integer if this String object lexicographically follows the argument string. The result is zero if the strings are equal; compareTo returns 0 exactly when the equals(Object) method would return true.
as you can see what happens is when "str10"
is compared to "str9"
the Unicode value of '1'
in "str10"
is less than the Unicode value of '9'
in "str9"
which is why you're getting the outcome "str10"
is not greater than "str9"
.
you could look into The Alphanum Algorithm as an alternative.
Upvotes: 2