Forums Register Login

Compare() - from Master Exam

+Pie Number of slices to send: Send
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
+Pie Number of slices to send: Send
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.
+Pie Number of slices to send: Send
I meant to say s1.charAt(1) = 'a' and s2.charAt(1) ='o'
+Pie Number of slices to send: Send
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?
+Pie Number of slices to send: Send
Right
+Pie Number of slices to send: Send
THanks
When people don’t understand what you are doing they call you crazy. But this tiny ad just doesn't care:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 816 times.
Similar Threads
Comparator Doubt
comparator problem
Can I sort String arrays?
Sorting
Comparator
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 09:57:49.