• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

comparator problem

 
sweety sinha
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
this question is from Master Exam, Test prep software

import java.util.*;
class comp2
{
public static void main(String []args)
{
String words[] = {"Good","Bad","Ugly"};
Comparator<String> best = new Comparator<String>(){
public int compare(String s1, String s2)
{
return s2.charAt(1)-s1.charAt(1);//what is happening here?
}
};
Arrays.sort(words, best);
System.out.println(words[0]);
}
}

what is happening in the question? please help
thanks in advance
 
ramesh maredu
Ranch Hand
Posts: 210
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

here you are comparing in reverse order. String class charAt() method will find the character value in specified location.remember charater is also integer value only, so you can do like
int i= 'a'-'a';
 
VidyaVikas Yalamanchili
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
HI

In the above code compare should always return a int.When you operate on characters every character can convert to an int.

you can give int i='a'

which will get i value 97.it is the ascii for a.So when you do s.charAt[1]-s.charAt[1] the sort happens on the second character of the string.
 
sweety sinha
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i get a little bit.
so is it doing like this:-
s2.charAt(1)="Ugly" - s1.charAt(1)="Bad"

please explain
 
Pranav Bhatt
Ranch Hand
Posts: 284
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
by Sweety
so is it doing like this:-
s2.charAt(1)="Ugly" - s1.charAt(1)="Bad"


Try adding the bold line below you will get to know.


The output of this is as-:
g a
o a
o g

[ September 15, 2008: Message edited by: Pranav Bhatt ]
 
arulk pillai
Author
Ranch Hand
Posts: 3393
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator



Basically it is doing a revers sort based on the second character of each word. charAt is 0 based. so 1 means second character and 0 means first character.

The comparator method returns 0 if 2 objects are equal and a -ve value if s1 < s2 and +ve value if s1 > s2. For example if you have Bad as s1 & Ugly as s2


s2.charAt(1) = 'g' ascii value is 103
s1.charAt(1) ='a' ascii value is 97

check --> http://www.asciitable.com/


s2.charAt(1) - s1.charAt(1) = 6 is a positive number. Since it is a + ve number s1 > s2 that means Bad > Ugly. So you get this sorted as

Good --> Ugly --> Bad
 
sweety sinha
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks for your replies
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic