Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Compare() - from Master Exam

 
Nabila Mohammad
Ranch Hand
Posts: 664
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is from MasterExam

I am not sure what is going on in the Compare Method.
How is it doing the comparision.




The answer is good
 
victor kamat
Ranch Hand
Posts: 247
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public int compare(String s1,String s2)
{
return s2.charAt(1)-s1.charAt(1);
}

In the code above, say s1="cat", and s2="dog".
The s2.charAt(1) = 'a' and s1.charAt(1)='o'.
Therefore compare() will return the int value of 'o'-'a'.

Note that compare() does not account for when s1 or s2 or both have length 1 or 0. It should have code to take care of these situations and also when either or both of them are null.
 
victor kamat
Ranch Hand
Posts: 247
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I meant to say s1.charAt(1) = 'a' and s2.charAt(1) ='o'
 
Nabila Mohammad
Ranch Hand
Posts: 664
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So that means its comparing the three words in (reverse of )Alphabetical order based on the second letter as its
s2.charAt(1) -s1.charAt(1)
and not
s1.charAt(1) -s2.charAt(1).

Right?
 
victor kamat
Ranch Hand
Posts: 247
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Right
 
Nabila Mohammad
Ranch Hand
Posts: 664
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
THanks
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic