• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

Comparator Doubt

 
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Sheriff
Posts: 11343
Mac Safari Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic