wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes doubt.... Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "doubt...." Watch "doubt...." New topic
Author

doubt....

disha arora
Greenhorn

Joined: Sep 06, 2008
Posts: 12
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
Rekha Srinath
Ranch Hand

Joined: Sep 13, 2008
Posts: 178
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).
disha arora
Greenhorn

Joined: Sep 06, 2008
Posts: 12
gudd explanation..got it.....thankz dear..
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: doubt....