• 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:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Jeanne Boyarsky
  • Ron McLeod
Sheriffs:
  • Paul Clapham
  • Liutauras Vilda
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
Bartenders:

Dount in K&B exam question

 
Ranch Hand
Posts: 361
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


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
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hmm...I kinda get it now..thanks naseem
 
Beauty is in the eye of the tiny ad.
We need your help - Coderanch server fundraiser
https://coderanch.com/wiki/782867/Coderanch-server-fundraiser
reply
    Bookmark Topic Watch Topic
  • New Topic