Following is a question from K&B mock exam.
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);
}
};
Arrays.sort(words, best);
System.out.println(words[0]);
}
}
ANS: Good
I'm always confused with Comparator. I could not get what exactly the s2.charAt(1) - s1.charAt(1); will do. How exactly it'll reverse the list? If it reverses the list then the list should be {"Ugly", "Bad", "Good"}. In this case, the words[0] should be-- Ugly.
Anyone, pls. clarify this to me - How the output is 'GOOD'?