Forums Register Login

doubt....

+Pie Number of slices to send: Send
Hi all,
Can anyone please help me out with compare() and compareTo() method..i m a bit confused with their implementations as in when and where to use which method..

thnx in advance
+Pie Number of slices to send: Send
Disha,
compareTo() is implemented when you use the Comparable interface--This is used if it is sufficient to sort your collection based on just one criteria/object key/field.

compare() -- implemented in Comparator interface. You can define different classes for each of your criteria and thus it enables you to sort your collection in many different ways.

For eg, if you have a collection that stores Employee details. If you want to sort this collection based on only the Employee ID, then you might use Comparable interface.

On the other hand, if you want to have two methods--one for sorting the collection based on Employee's first name and the other method for sorting based on Employee's last name, you need to use Comparator interface. Inside the compare() method of Comparator implementation class, you mention what is the criteria for comparison (whether ID, first name or last name).
+Pie Number of slices to send: Send
gudd explanation..got it.....thankz dear..
It sure was nice of your sister to lend us her car. Let's show our appreciation by sharing this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 1147 times.
Similar Threads
Finalization Method
NX: When should I throw DuplicateKeyException?
garbage collection
Sharpen your Pencil - Page 323 in HFEJB
Changin font in a JTextArea
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 07:33:32.