This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Comparator Doubt Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Comparator Doubt" Watch "Comparator Doubt" New topic
Author

Comparator Doubt

Mercurio Savedra
Greenhorn

Joined: Dec 04, 2005
Posts: 25
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

Joined: Aug 31, 2004
Posts: 11343

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.


"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
ramesh vardhan
Greenhorn

Joined: Jun 21, 2005
Posts: 6
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.


Regards,<br />RAMESH VARDHAN.
ramesh vardhan
Greenhorn

Joined: Jun 21, 2005
Posts: 6
For the purpose of explanation i used s2[ind] instead of s2.charAt(ind).

Please do not confuse.Sorry if I have already created.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Comparator Doubt
 
Similar Threads
Compare() - from Master Exam
comparator problem
Sorting and Comparators
Sorting
Dount in K&B exam question