Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Comparator Doubt

 
Mercurio Savedra
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
import java.util.*;

class Comp2{

public static void main(Strig [] 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);
}
};
Arrays.sort(words,best);
System.out.println(words[0]);
}

}

Somebody could explain me why K & B test said that this order the collection in reverse order i am very confused
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Raul Morales:
... Somebody could explain me why K & B test said that this order the collection in reverse order...

In a String, the indexing of characters starts at zero. So notice that the array is being sorted based on the second letter (charAt(1)) of each String. Here's the code with some lines added to show how the Comparator is working.
 
ramesh vardhan
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The comparator arrange the strings in reverse order as s2[ind]-s1[ind] is being done.i.e when s2[ind] is 'b' and s1[ind] is 'a', then the compare method returns positive integer('b'-'a') saying 'b' > 'a'(reverse order).

And the character under concern is of index 1.so the order '0'>'g'>'a'.
Otherwise - Good>Ugly>bad.

Hope this is clear.
 
ramesh vardhan
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For the purpose of explanation i used s2[ind] instead of s2.charAt(ind).

Please do not confuse.Sorry if I have already created.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic