Java using compareTo with an array of strings
I was wondering if the compareTo method looks at just the length of the strings or if it looks at each character of the string?
and if it does just look at the length how would i be able to compare two elements in an array of strings to see which element is bigger.
What im trying to do is write a method that recursively looks at the right side of the array, the middle, and the left and 开发者_如何学编程returns the index of the longest string in the array.
i have it working fine, the only problem is when there are two strings of the same length, it returns the first one.
Just clarifying how the compareTo method looks at the strings would help me solve this problem i think
how do strings of numbers compare lexographically? would 17 be bigger than 15?
compareTo
for strings is done lexicographically. (or alphabetically) It doesn't compare the lengths of the strings.
A is less than B if A is alphabetically before B.
If you want to compare the length of a string, you can get the length from the .length()
method and compare it as an integer.
EDIT:
Lexicographically is done by the ASCII/UNICODE values.
So in your example, 17
is bigger than 15
. Because the 1
is the same (a tie), and 7
has a higher ASCII/UNICODE value than 5
.
compareTo
will compare both the alphabetical (lexicographical) order of the strings.
See the documentation here.
I was wondering if the compareTo method looks at just the length of the strings or if it looks at each character of the string?
It (potentially) looks at each character in the string. It certainly does not just look at the length.
and if it does just look at the length how would i be able to compare two elements in an array of strings to see which element is bigger.
It doesn't, so this question is moot.
What im trying to do is write a method that recursively looks at the right side of the array, the middle, and the left and returns the index of the longest string in the array.
i have it working fine, the only problem is when there are two strings of the same length, it returns the first one.
We'd need to see your code to understand what is actually going wrong, but it is most likely not caused by some strangeness in the semantics of String.compareTo(String)
how do strings of numbers compare lexographically? would 17 be bigger than 15?
Yes it does compare strings lexicographically. Yes "17" would be bigger than "15". (But "17" would be greater than "15" if you compared the strings numerically too. On the other hand "7" is lexicographically greater than "13" but numerically less than it.)
Perhaps you need to read up on what "lexicographical order" means; Wikipedia summarizes it as:
"In mathematics, the lexicographic or lexicographical order, (also known as lexical order, dictionary order, alphabetical order or lexicographic(al) product), is a generalization of the way the alphabetical order of words is based on the alphabetical order of letters."
精彩评论