Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialkemishobowale
3,627 Points"banana".compareTo("apple") sorting question
I'm confused to why "banana".compareTo("apple") results in 1 since apple or 'a' comes first in the alphabet. Why is banana greater??
2 Answers
Leandro Botella Penalva
17,618 PointsHi Kemi,
The compareTo method can return the following values:
-A number lower than 0 if the first string goes before the second
-0 if both strings are equal
-A number greater than 0 if the first string goes after the second
So in this case "banana".compareTo("apple") would return a positive value (1) because "banana" is 1 time greater than "apple". On the contrary, "apple".compareTo("banana") would return a negative value (-1) because "apple" is 1 time lower than "banana"
Nathaniel Evans
14,205 PointsThanks Leandro, I thought it was because the compareTo method was sorting by string length (in which case "banana" has 6 chars, and "apple" has 5, therefore banana is greater than apple). Glad to have the right answer!
kemishobowale
3,627 Pointskemishobowale
3,627 PointsThank you Leandro
However, i still do not understand why it is greater or why it is lower. On what basis? Alphabetically? Because to me, A is greater than B or Apple is greater than Banana, alphabetically anyway. I just fear i will not use the compareTo method correctly if i do not understand what /how it is being compared...
Leandro Botella Penalva
17,618 PointsLeandro Botella Penalva
17,618 PointsEach character has a position in the Unicode table. The letter "a" has the position 61 and the "b" has the position 62. Then what compare to does is subtract both positions to determine how much difference in positions there is between both characters.
"banana".compareTo("apple")
b (62) - a (61) = 1 (one position after)
"apple".compareTo("banana")
a (61) - b (62) = -1 (one position before)
"apple".compareTo("apple")
a (61) - a (61) = 0 (equal)
If the first character is equal in both words, compareTo will try to do the subtraction from the second character and if these ones are equal it will try with the third and so on until it finds a difference or if there is no difference will return 0.
kemishobowale
3,627 Pointskemishobowale
3,627 PointsExcellent. Thats the crucial part i was missing...was the whole Unicode thing. Thank you for helping me understand