posted 18 years ago
If compare() method returns negative number, it means s1 < s2
When comparator compares "Good" and "Bad". s1 = "Good" and s2 = "Bad"
i.e., "Good" will be assigned to s1 and "Bad" to s2.
s2.charAt(1) will give you 'a'
s1.chatAt(1) will return 'o'
ASCII equivalent of 'a' is 97 and that of 'o' is 111. So difference i.e., 'a' - 'o' is negative.
Since number is negative, therefore s1 is less than s2. (No sorting)
Second case is the comparison between "Bad" & "Ugly".
Again s2.chatAt(1) is 'g' and s1.chatAt(1) is 'a'
'g' - 'a' is positive and g comes after a in ASCII characters. So difference is going to be positive number. It means here s1 > s2
Therefore after sorting, the array will be {"Good", "Ugly", "Bad"}
Naseem