Win a copy of Head First Android this week in the Android forum!
  • 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:
  • Tim Cooke
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • Rob Spoor
  • Bear Bibeault
Saloon Keepers:
  • Jesse Silverman
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
Bartenders:
  • Piet Souris
  • Al Hobbs
  • salvin francis

doubt....

 
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Ranch Hand
Posts: 178
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
gudd explanation..got it.....thankz dear..
 
You showed up just in time for the waffles! And this tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
reply
    Bookmark Topic Watch Topic
  • New Topic