• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

a question about a String method...

 
Lawrence Buensalida
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Guys, question...

I don't know the use of the String method compareTo(String anotherstring).
What's the simplest explanation for this method and how do I use this, I find the j2me explanation hard to understand.

Thanks.
 
Shawn Fitzgerald
author
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The compareTo method is used for sorting. The return values are -1, 0, 1, to denote the order that the String the method is called on in relationship to the provided parameter String.

Thus:
String a = "a";
String b = "b";
System.out.println("a.compareTo(b)="+a.compareTo(b));
System.out.println("b.compareTo(a)="+b.compareTo(a));

output would be:
a.compareTo(b)=-1
b.compareTo(a)=1

However it should be noted that the spec only says in the first case the value is less than 0, and in the second case is greater than 0. So you should expect values like -5 or if 'b' in the above example was 'c' the values would be -2 and 2.

regards,
-Shawn
 
lexander Bosco
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hmm i think the compareTo method uses d first character in a string to do the comparison.

like character 'a' = 1, 'b'=2, 'c' =3 ....and so on so comparing
Come with France will get you something like -3
reverse will be 3
hope u get?
 
Lawrence Buensalida
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
lex,

was the string "abc" compared to "Come with France" for that matter? In which case, "c" was the reason why the result is 3, is that it?
 
Shawn Fitzgerald
author
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Almost, it uses the first character that doesn't match.

So if you compare "france" with "frank", you compare 'c' to 'k'
and the difference is -8.

c d e f g h i j k
0 1 2 3 4 5 6 7 8

while comparing "sam" and "san" compares 'm' to 'n' and would
return a -1.

m n o
0 1 2

Does that give you a better picture?
-Shawn
 
Lawrence Buensalida
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
YES!!! wooosh...there goes confusion.



I got it!

I didn't understood it before this example because the "get it" function of my brain is slow...but now I got the right explanation.

Thanks Shawn
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic