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:
• Campbell Ritchie
• Jeanne Boyarsky
• Ron McLeod
• Paul Clapham
• Liutauras Vilda
Sheriffs:
• paul wheaton
• Rob Spoor
• Devaka Cooray
Saloon Keepers:
• Stephan van Hulst
• Tim Holloway
• Carey Brown
• Frits Walraven
• Tim Moores
Bartenders:
• Mikalai Zaikin

# Dount in K&B exam question

Ranch Hand
Posts: 361
• Number of slices to send:
Optional 'thank-you' note:

I dont get how the output is 'Good'. In this code we are passing an array and a comparator to the Arrays.sort() which will call the compare method and in there we are reversing order but I dont quite get the process of it.(Im a little confused with what charAt() is doing.). Are we reversing order based on 2nd character of GOod with that of bAd and uGly?? Can someone give me a step by step of how the o/p of 'good' is being achieved.

Ranch Hand
Posts: 809
• Number of slices to send:
Optional 'thank-you' note:

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

Amit Batra
Ranch Hand
Posts: 361
• Number of slices to send:
Optional 'thank-you' note:
hmm...I kinda get it now..thanks naseem

 Willie Smits increased rainfall 25% in three years by planting trees. Tiny ad: a bit of art, as a gift, the permaculture playing cards https://gardener-gift.com